forked from Drewol/unnamed-sdvx-clone
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMapDatabase.cpp
2343 lines (2085 loc) · 65.8 KB
/
MapDatabase.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 "stdafx.h"
#include "MapDatabase.hpp"
#include "Database.hpp"
#include "Beatmap.hpp"
#include "TinySHA1.hpp"
#include "Shared/Profiling.hpp"
#include "Shared/Files.hpp"
#include "Shared/Time.hpp"
#include "KShootMap.hpp"
#include <thread>
#include <mutex>
#include <chrono>
#include <atomic>
#include <iostream>
#include <fstream>
#include <condition_variable>
using std::thread;
using std::mutex;
using namespace std;
class MapDatabase_Impl
{
public:
// For calling delegates
MapDatabase& m_outer;
thread m_thread;
condition_variable m_cvPause;
mutex m_pauseMutex;
std::atomic<bool> m_paused;
bool m_searching = false;
bool m_interruptSearch = false;
Set<String> m_searchPaths;
Database m_database;
Map<int32, FolderIndex*> m_folders;
Map<int32, ChartIndex*> m_charts;
Map<int32, ChallengeIndex*> m_challenges;
Map<int32, PracticeSetupIndex*> m_practiceSetups;
Map<String, ChartIndex*> m_chartsByHash;
Map<String, FolderIndex*> m_foldersByPath;
Multimap<int32, PracticeSetupIndex*> m_practiceSetupsByChartId;
int32 m_nextFolderId = 1;
int32 m_nextChartId = 1;
int32 m_nextChalId = 1;
String m_sortField = "title";
bool m_transferScores = true;
struct SearchState
{
struct ExistingFileEntry
{
int32 id;
uint64 lwt;
};
// Maps file paths to the id's and last write time's for difficulties already in the database
Map<String, ExistingFileEntry> difficulties;
Map<String, ExistingFileEntry> challenges;
} m_searchState;
// Represents an event produced from a scan
// a difficulty can be removed/added/updated
// a BeatmapSettings structure will be provided for added/updated events
struct Event
{
enum Type{
Chart,
Challenge
};
Type type;
enum Action
{
Added,
Removed,
Updated
};
Action action;
String path;
// Current lwt of file
uint64 lwt;
// Id of the map
int32 id;
// Scanned map data, for added/updated maps
BeatmapSettings* mapData = nullptr;
nlohmann::json json;
String hash;
};
List<Event> m_pendingChanges;
mutex m_pendingChangesLock;
static const int32 m_version = 20;
public:
MapDatabase_Impl(MapDatabase& outer, bool transferScores) : m_outer(outer)
{
m_transferScores = transferScores;
String databasePath = Path::Absolute("maps.db");
if(!m_database.Open(databasePath))
{
Logf("Failed to open database [%s]", Logger::Severity::Warning, databasePath);
assert(false);
}
m_paused.store(false);
bool rebuild = false;
bool update = false;
DBStatement versionQuery = m_database.Query("SELECT version FROM `Database`");
int32 gotVersion = 0;
if(versionQuery && versionQuery.Step())
{
gotVersion = versionQuery.IntColumn(0);
if(gotVersion != m_version)
{
update = true;
}
}
else
{
// Create DB
m_database.Exec("DROP TABLE IF EXISTS Database");
m_database.Exec("CREATE TABLE Database(version INTEGER)");
m_database.Exec(Utility::Sprintf("INSERT OR REPLACE INTO Database(rowid, version) VALUES(1, %d)", m_version));
rebuild = true;
}
versionQuery.Finish();
if(rebuild)
{
m_CreateTables();
// Update database version
m_database.Exec(Utility::Sprintf("UPDATE Database SET `version`=%d WHERE `rowid`=1", m_version));
}
else if (update)
{
ProfilerScope $(Utility::Sprintf("Upgrading db (%d -> %d)", gotVersion, m_version));
//back up old db file
Path::Copy(Path::Absolute("maps.db"), Path::Absolute("maps.db_" + Shared::Time::Now().ToString() + ".bak"));
m_outer.OnDatabaseUpdateStarted.Call(1);
///TODO: Make loop for doing iterative upgrades
if (gotVersion == 8) //upgrade from 8 to 9
{
m_database.Exec("ALTER TABLE Scores ADD COLUMN hitstats BLOB");
gotVersion = 9;
}
if (gotVersion == 9) //upgrade from 9 to 10
{
m_database.Exec("ALTER TABLE Scores ADD COLUMN timestamp INTEGER");
gotVersion = 10;
}
if (gotVersion == 10) //upgrade from 10 to 11
{
m_database.Exec("ALTER TABLE Difficulties ADD COLUMN hash TEXT");
gotVersion = 11;
}
if (gotVersion == 11) //upgrade from 11 to 12
{
m_database.Exec("CREATE TABLE Collections"
"(collection TEXT, mapid INTEGER, "
"UNIQUE(collection,mapid), "
"FOREIGN KEY(mapid) REFERENCES Maps(rowid))");
gotVersion = 12;
}
if (gotVersion == 12) //upgrade from 12 to 13
{
int diffCount = 1;
{
// Do in its own scope so that it will destruct before we modify anything else
DBStatement diffCountStmt = m_database.Query("SELECT COUNT(rowid) FROM Difficulties");
if (diffCountStmt.StepRow())
{
diffCount = diffCountStmt.IntColumn(0);
}
}
m_outer.OnDatabaseUpdateProgress.Call(0, diffCount);
int progress = 0;
int totalScoreCount = 0;
DBStatement diffScan = m_database.Query("SELECT rowid,path FROM Difficulties");
Vector<ScoreIndex> scoresToAdd;
while (diffScan.StepRow())
{
if (progress % 16 == 0)
m_outer.OnDatabaseUpdateProgress.Call(progress, diffCount);
progress++;
bool noScores = true;
int diffid = diffScan.IntColumn(0);
String diffpath = diffScan.StringColumn(1);
DBStatement scoreCount = m_database.Query("SELECT COUNT(*) FROM scores WHERE diffid=?");
scoreCount.BindInt(1, diffid);
if (scoreCount.StepRow())
{
noScores = scoreCount.IntColumn(0) == 0;
}
if (noScores)
{
continue;
}
String hash;
File diffFile;
if (diffFile.OpenRead(diffpath))
{
char data_buffer[0x80];
uint32_t digest[5];
sha1::SHA1 s;
size_t amount_read = 0;
size_t read_size;
do
{
read_size = diffFile.Read(data_buffer, sizeof(data_buffer));
amount_read += read_size;
s.processBytes(data_buffer, read_size);
} while (read_size != 0);
s.getDigest(digest);
hash = Utility::Sprintf("%08x%08x%08x%08x%08x", digest[0], digest[1], digest[2], digest[3], digest[4]);
}
else {
Logf("Could not open chart file at \"%s\" scores will be lost.", Logger::Severity::Warning, diffpath);
continue;
}
DBStatement scoreScan = m_database.Query("SELECT rowid,score,crit,near,miss,gauge,gameflags,hitstats,timestamp,diffid FROM Scores WHERE diffid=?");
scoreScan.BindInt(1, diffid);
while (scoreScan.StepRow())
{
ScoreIndex score;
score.id = scoreScan.IntColumn(0);
score.score = scoreScan.IntColumn(1);
score.crit = scoreScan.IntColumn(2);
score.almost = scoreScan.IntColumn(3);
score.miss = scoreScan.IntColumn(4);
score.gauge = (float) scoreScan.DoubleColumn(5);
score.gaugeOption = scoreScan.IntColumn(6);
Buffer hitstats = scoreScan.BlobColumn(7);
score.timestamp = scoreScan.Int64Column(8);
auto timestamp = Shared::Time(score.timestamp);
score.chartHash = hash;
score.replayPath = Path::Normalize(Path::Absolute("replays/" + hash + "/" + timestamp.ToString() + ".urf"));
Path::CreateDir(Path::Absolute("replays/" + hash));
File replayFile;
if (replayFile.OpenWrite(score.replayPath))
{
replayFile.Write(hitstats.data(), hitstats.size());
}
else
{
Logf("Could not open replay file at \"%s\" replay data will be lost.", Logger::Severity::Warning, score.replayPath);
}
scoresToAdd.Add(score);
totalScoreCount++;
}
}
progress = 0;
m_database.Exec("DROP TABLE IF EXISTS Maps");
m_database.Exec("DROP TABLE IF EXISTS Difficulties");
m_CreateTables();
DBStatement addScore = m_database.Query("INSERT INTO Scores(score,crit,near,miss,gauge,gameflags,replay,timestamp,chart_hash) VALUES(?,?,?,?,?,?,?,?,?)");
m_database.Exec("BEGIN");
for (ScoreIndex& score : scoresToAdd)
{
addScore.BindInt(1, score.score);
addScore.BindInt(2, score.crit);
addScore.BindInt(3, score.almost);
addScore.BindInt(4, score.miss);
addScore.BindDouble(5, score.gauge);
addScore.BindInt(6, score.gaugeOption);
addScore.BindString(7, score.replayPath);
addScore.BindInt64(8, score.timestamp);
addScore.BindString(9, score.chartHash);
addScore.Step();
addScore.Rewind();
if (progress % 16 == 0)
{
m_outer.OnDatabaseUpdateProgress.Call(progress, totalScoreCount);
}
progress++;
}
m_database.Exec("END");
m_database.Exec("VACUUM");
gotVersion = 13;
}
if (gotVersion == 13) //from 13 to 14
{
m_database.Exec("ALTER TABLE Charts ADD COLUMN custom_offset INTEGER");
m_database.Exec("ALTER TABLE Scores ADD COLUMN user_name TEXT");
m_database.Exec("ALTER TABLE Scores ADD COLUMN user_id TEXT");
m_database.Exec("ALTER TABLE Scores ADD COLUMN local_score INTEGER");
m_database.Exec("UPDATE Charts SET custom_offset=0");
m_database.Exec("UPDATE Scores SET local_score=1");
m_database.Exec("UPDATE Scores SET local_score=1");
m_database.Exec("UPDATE Scores SET user_name=\"\"");
m_database.Exec("UPDATE Scores SET user_id=\"\"");
gotVersion = 14;
}
if (gotVersion == 14)
{
m_database.Exec("CREATE TABLE PracticeSetups ("
"chart_id INTEGER,"
"setup_title TEXT,"
"loop_success INTEGER,"
"loop_fail INTEGER,"
"range_begin INTEGER,"
"range_end INTEGER,"
"fail_cond_type INTEGER,"
"fail_cond_value INTEGER,"
"playback_speed REAL,"
"inc_speed_on_success INTEGER,"
"inc_speed REAL,"
"inc_streak INTEGER,"
"dec_speed_on_fail INTEGER,"
"dec_speed REAL,"
"min_playback_speed REAL,"
"max_rewind INTEGER,"
"max_rewind_measure INTEGER,"
"FOREIGN KEY(chart_id) REFERENCES Charts(rowid)"
")");
gotVersion = 15;
}
if (gotVersion == 15)
{
m_database.Exec("ALTER TABLE Scores ADD COLUMN window_perfect INTEGER");
m_database.Exec("ALTER TABLE Scores ADD COLUMN window_good INTEGER");
m_database.Exec("ALTER TABLE Scores ADD COLUMN window_hold INTEGER");
m_database.Exec("ALTER TABLE Scores ADD COLUMN window_miss INTEGER");
m_database.Exec("UPDATE Scores SET window_perfect=46");
m_database.Exec("UPDATE Scores SET window_good=150");
m_database.Exec("UPDATE Scores SET window_hold=150");
m_database.Exec("UPDATE Scores SET window_miss=300");
gotVersion = 16;
}
if (gotVersion == 16)
{
m_database.Exec("CREATE TABLE Challenges"
"("
"title TEXT,"
"charts TEXT,"
"chart_meta TEXT," // used for search
"clear_mark INTEGER,"
"best_score INTEGER,"
"req_text TEXT,"
"path TEXT,"
"hash TEXT,"
"level INTEGER,"
"lwt INTEGER"
")");
gotVersion = 17;
}
if (gotVersion == 17)
{
Map<int32, PlaybackOptions> optionMap;
int totalScoreCount = 0;
DBStatement scoreScan = m_database.Query("SELECT rowid,gameflags FROM Scores");
while (scoreScan.StepRow())
{
optionMap.Add(scoreScan.IntColumn(0), PlaybackOptions::FromFlags(scoreScan.IntColumn(1)));
totalScoreCount++;
}
m_outer.OnDatabaseUpdateProgress.Call(0, totalScoreCount);
int progress = 0;
//alter table.
// if we were on a newer sqlite version the gameflags column could easily be renamed but it will
// instead still exist in the db after this update but will be unused.
m_database.Exec("BEGIN");
m_database.Exec("ALTER TABLE Scores ADD COLUMN gauge_type INTEGER");
m_database.Exec("ALTER TABLE Scores ADD COLUMN auto_flags INTEGER");
m_database.Exec("ALTER TABLE Scores ADD COLUMN gauge_opt INTEGER");
m_database.Exec("ALTER TABLE Scores ADD COLUMN mirror INTEGER");
m_database.Exec("ALTER TABLE Scores ADD COLUMN random INTEGER");
DBStatement setScoreOpt = m_database.Query("UPDATE Scores set gauge_type=?, gauge_opt=?, mirror=?, random=?, auto_flags=? WHERE rowid=?");
for (auto& o : optionMap)
{
setScoreOpt.BindInt(1, (int32)o.second.gaugeType);
setScoreOpt.BindInt(2, o.second.gaugeOption);
setScoreOpt.BindInt(3, o.second.mirror ? 1 : 0);
setScoreOpt.BindInt(4, o.second.random ? 1 : 0);
setScoreOpt.BindInt(5, (int32)o.second.autoFlags);
setScoreOpt.BindInt(6, o.first);
setScoreOpt.StepRow();
setScoreOpt.Rewind();
progress++;
m_outer.OnDatabaseUpdateProgress.Call(progress, totalScoreCount);
}
m_database.Exec("END");
gotVersion = 18;
}
if (gotVersion == 18)
{
m_database.Exec("ALTER TABLE Scores ADD COLUMN window_slam INTEGER");
m_database.Exec("UPDATE Scores SET window_slam=84");
gotVersion = 19;
}
if (gotVersion == 19)
{
m_database.Exec("UPDATE Scores SET window_good=150 WHERE window_good=92");
m_database.Exec("UPDATE Scores SET window_hold=150 WHERE window_hold=138");
m_database.Exec("UPDATE Scores SET window_miss=300 WHERE window_miss=250");
m_database.Exec("UPDATE Scores SET window_slam=84 WHERE window_slam=75");
gotVersion = 20;
}
m_database.Exec(Utility::Sprintf("UPDATE Database SET `version`=%d WHERE `rowid`=1", m_version));
m_outer.OnDatabaseUpdateDone.Call();
}
else
{
// NOTE: before we loaded the database here. This was redundant since we always do StartSearching
// Plus we don't do this when doing an update so if it was a problem to not do it here we would
// have already noticed it being broken in a launch where the db is updated
// Also with challenges we can't do this until the constructor is done so we can access the
// MapDatabase wrapper while loading challenges
//m_LoadInitialData();
}
}
~MapDatabase_Impl()
{
StopSearching();
m_CleanupMapIndex();
//discard pending changes, probably should apply them(?)
auto changes = FlushChanges();
for (auto& c : changes)
{
if(c.mapData)
delete c.mapData;
}
}
void StartSearching()
{
if(m_searching)
return;
if(m_thread.joinable())
m_thread.join();
// Apply previous diff to prevent duplicated entry
Update();
// Create initial data set to compare to when evaluating if a file is added/removed/updated
m_LoadInitialData();
ResumeSearching();
m_interruptSearch = false;
m_searching = true;
m_thread = thread(&MapDatabase_Impl::m_SearchThread, this);
}
void StopSearching()
{
ResumeSearching();
m_interruptSearch = true;
m_searching = false;
if(m_thread.joinable())
{
m_thread.join();
}
}
void AddSearchPath(const String& path)
{
String normalizedPath = Path::Normalize(Path::Absolute(path));
if(m_searchPaths.Contains(normalizedPath))
return;
m_searchPaths.Add(normalizedPath);
}
void RemoveSearchPath(const String& path)
{
String normalizedPath = Path::Normalize(Path::Absolute(path));
if(!m_searchPaths.Contains(normalizedPath))
return;
m_searchPaths.erase(normalizedPath);
}
/* Thread safe event queue functions */
// Add a new change to the change queue
void AddChange(Event change)
{
m_pendingChangesLock.lock();
m_pendingChanges.emplace_back(change);
m_pendingChangesLock.unlock();
}
// Removes changes from the queue and returns them
// additionally you can specify the maximum amount of changes to remove from the queue
List<Event> FlushChanges(size_t maxChanges = -1)
{
List<Event> changes;
m_pendingChangesLock.lock();
if(maxChanges == -1)
{
changes = std::move(m_pendingChanges); // All changes
}
else
{
for(size_t i = 0; i < maxChanges && !m_pendingChanges.empty(); i++)
{
changes.AddFront(m_pendingChanges.front());
m_pendingChanges.pop_front();
}
}
m_pendingChangesLock.unlock();
return std::move(changes);
}
// TODO(itszn) make sure this is not case sensitive
ChartIndex* FindFirstChartByPath(const String& searchString)
{
String stmt = "SELECT DISTINCT rowid FROM Charts WHERE path LIKE ? LIMIT 1";
DBStatement search = m_database.Query(stmt);
search.BindString(1, "%"+searchString+"%");
while(search.StepRow())
{
int32 id = search.IntColumn(0);
ChartIndex** chart = m_charts.Find(id);
if (!chart)
return nullptr;
return *chart;
}
return nullptr;
}
ChartIndex* FindFirstChartByNameAndLevel(const String& name, uint32 level, bool exact=true)
{
String stmt = "SELECT DISTINCT rowid FROM Charts WHERE title LIKE ? and level=? LIMIT 1";
DBStatement search = m_database.Query(stmt);
if (exact)
search.BindString(1, name);
else
search.BindString(1, "%"+name+"%");
search.BindInt(2, level);
while(search.StepRow())
{
int32 id = search.IntColumn(0);
ChartIndex** chart = m_charts.Find(id);
if (!chart)
return nullptr;
return *chart;
}
// Try non exact now
if (exact)
return FindFirstChartByNameAndLevel(name, level, false);
return nullptr;
}
ChartIndex* FindFirstChartByHash(const String& hash)
{
ChartIndex** chart = m_chartsByHash.Find(hash);
if (!chart)
return nullptr;
return *chart;
}
Map<int32, FolderIndex*> FindFoldersByHash(const String& hash)
{
String stmt = "SELECT DISTINCT folderId FROM Charts WHERE hash = ?";
DBStatement search = m_database.Query(stmt);
search.BindString(1, hash);
Map<int32, FolderIndex*> res;
while (search.StepRow())
{
int32 id = search.IntColumn(0);
FolderIndex** folder = m_folders.Find(id);
if (folder)
{
res.Add(id, *folder);
}
}
return res;
}
// TODO(itszn) make this not case sensitive
Map<int32, FolderIndex*> FindFoldersByPath(const String& searchString)
{
String stmt = "SELECT DISTINCT folderId FROM Charts WHERE path LIKE ?";
DBStatement search = m_database.Query(stmt);
search.BindString(1, "%" + searchString + "%");
Map<int32, FolderIndex*> res;
while(search.StepRow())
{
int32 id = search.IntColumn(0);
FolderIndex** folder = m_folders.Find(id);
if(folder)
{
res.Add(id, *folder);
}
}
return res;
}
Map<int32, ChallengeIndex*> FindChallenges(const String& searchString)
{
WString test = Utility::ConvertToWString(searchString);
String stmt = "SELECT DISTINCT rowid FROM Challenges WHERE";
Vector<String> terms = searchString.Explode(" ");
int32 i = 0;
for (auto term : terms)
{
if (i > 0)
stmt += " AND";
stmt += String(" (title LIKE ?") +
" OR chart_meta LIKE ?"
" OR path LIKE ?)";
i++;
}
DBStatement search = m_database.Query(stmt);
i = 1;
for (auto term : terms)
{
// Bind all the terms
for (int j = 0; j < 3; j++)
{
search.BindString(i+j, "%" + term + "%");
}
i+=6;
}
Map<int32, ChallengeIndex*> res;
while(search.StepRow())
{
int32 id = search.IntColumn(0);
ChallengeIndex** challenge = m_challenges.Find(id);
if(challenge)
{
res.Add(id, *challenge);
}
}
return res;
}
Map<int32, FolderIndex*> FindFolders(const String& searchString)
{
WString test = Utility::ConvertToWString(searchString);
String stmt = "SELECT DISTINCT folderId FROM Charts WHERE";
Vector<String> terms = searchString.Explode(" ");
int32 i = 0;
for(auto term : terms)
{
if(i > 0)
stmt += " AND";
stmt += String(" (artist LIKE ?") +
" OR title LIKE ?" +
" OR path LIKE ?" +
" OR effector LIKE ?" +
" OR artist_translit LIKE ?" +
" OR title_translit LIKE ?)";
i++;
}
DBStatement search = m_database.Query(stmt);
i = 1;
for (auto term : terms)
{
// Bind all the terms
for (int j = 0; j < 6; j++)
{
search.BindString(i+j, "%" + term + "%");
}
i+=6;
}
Map<int32, FolderIndex*> res;
while(search.StepRow())
{
int32 id = search.IntColumn(0);
FolderIndex** folder = m_folders.Find(id);
if(folder)
{
res.Add(id, *folder);
}
}
return res;
}
Vector<String> GetCollections()
{
Vector<String> res;
DBStatement search = m_database.Query("SELECT DISTINCT collection FROM collections");
while (search.StepRow())
{
res.Add(search.StringColumn(0));
}
return res;
}
Vector<String> GetCollectionsForMap(int32 mapid)
{
Vector<String> res;
DBStatement search = m_database.Query(Utility::Sprintf("SELECT DISTINCT collection FROM collections WHERE folderid==%d", mapid));
while (search.StepRow())
{
res.Add(search.StringColumn(0));
}
return res;
}
Vector<PracticeSetupIndex*> GetOrAddPracticeSetups(int32 chartId)
{
Vector<PracticeSetupIndex*> res;
auto it = m_practiceSetupsByChartId.equal_range(chartId);
for (auto it1 = it.first; it1 != it.second; ++it1)
{
res.Add(it1->second);
}
if (res.empty())
{
PracticeSetupIndex* practiceSetup = new PracticeSetupIndex();
practiceSetup->id = -1;
practiceSetup->chartId = chartId;
practiceSetup->setupTitle = "";
practiceSetup->loopSuccess = 0;
practiceSetup->loopFail = 1;
practiceSetup->rangeBegin = 0;
practiceSetup->rangeEnd = 0;
practiceSetup->failCondType = 0;
practiceSetup->failCondValue = 0;
practiceSetup->playbackSpeed = 1.0;
practiceSetup->incSpeedOnSuccess = 0;
practiceSetup->incSpeed = 0.0;
practiceSetup->incStreak = 1;
practiceSetup->decSpeedOnFail = 0;
practiceSetup->decSpeed = 0.0;
practiceSetup->minPlaybackSpeed = 0.1;
practiceSetup->maxRewind = 0;
practiceSetup->maxRewindMeasure = 1;
UpdateOrAddPracticeSetup(practiceSetup);
res.emplace_back(practiceSetup);
}
return res;
}
Map<int32, FolderIndex*> FindFoldersByCollection(const String& collection)
{
String stmt = "SELECT folderid FROM Collections WHERE collection==?";
DBStatement search = m_database.Query(stmt);
search.BindString(1, collection);
Map<int32, FolderIndex*> res;
while (search.StepRow())
{
int32 id = search.IntColumn(0);
FolderIndex** folder = m_folders.Find(id);
if (folder)
{
res.Add(id, *folder);
}
}
return res;
}
Map<int32, FolderIndex*> FindFoldersByFolder(const String& folder)
{
char csep[2];
csep[0] = Path::sep;
csep[1] = 0;
String sep(csep);
String stmt = "SELECT rowid FROM folders WHERE path LIKE ?";
DBStatement search = m_database.Query(stmt);
search.BindString(1, "%" + sep + folder + sep + "%");
Map<int32, FolderIndex*> res;
while (search.StepRow())
{
int32 id = search.IntColumn(0);
FolderIndex** folder = m_folders.Find(id);
if (folder)
{
res.Add(id, *folder);
}
}
return res;
}
// Processes pending database changes
void Update()
{
List<Event> changes = FlushChanges();
if(changes.empty())
return;
DBStatement addChart = m_database.Query("INSERT INTO Charts("
"folderId,path,title,artist,title_translit,artist_translit,jacket_path,effector,illustrator,"
"diff_name,diff_shortname,bpm,diff_index,level,hash,preview_file,preview_offset,preview_length,lwt) "
"VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
DBStatement addFolder = m_database.Query("INSERT INTO Folders(path,rowid) VALUES(?,?)");
DBStatement addChallenge = m_database.Query("INSERT INTO Challenges("
"title,charts,chart_meta,clear_mark,best_score,req_text,path,hash,level,lwt) "
"VALUES(?,?,?,?,?,?,?,?,?,?)");
DBStatement update = m_database.Query("UPDATE Charts SET path=?,title=?,artist=?,title_translit=?,artist_translit=?,jacket_path=?,effector=?,illustrator=?,"
"diff_name=?,diff_shortname=?,bpm=?,diff_index=?,level=?,hash=?,preview_file=?,preview_offset=?,preview_length=?,lwt=? WHERE rowid=?"); //TODO: update
DBStatement updateChallenge = m_database.Query("UPDATE Challenges SET title=?,charts=?,chart_meta=?,clear_mark=?,best_score=?,req_text=?,path=?,hash=?,level=?,lwt=? WHERE rowid=?");
DBStatement removeChart = m_database.Query("DELETE FROM Charts WHERE rowid=?");
DBStatement removeChallenge = m_database.Query("DELETE FROM Challenges WHERE rowid=?");
DBStatement removeFolder = m_database.Query("DELETE FROM Folders WHERE rowid=?");
DBStatement scoreScan = m_database.Query("SELECT "
"rowid,score,crit,near,miss,gauge,auto_flags,replay,timestamp,chart_hash,user_name,user_id,local_score,window_perfect,window_good,window_hold,window_miss,window_slam,gauge_type,gauge_opt,mirror,random "
"FROM Scores WHERE chart_hash=?");
DBStatement moveScores = m_database.Query("UPDATE Scores set chart_hash=? where chart_hash=?");
Set<FolderIndex*> addedChartEvents;
Set<FolderIndex*> removeChartEvents;
Set<FolderIndex*> updatedChartEvents;
Set<ChallengeIndex*> addedChalEvents;
Set<ChallengeIndex*> removeChalEvents;
Set<ChallengeIndex*> updatedChalEvents;
const String diffShortNames[4] = { "NOV", "ADV", "EXH", "INF" };
const String diffNames[4] = { "Novice", "Advanced", "Exhaust", "Infinite" };
m_database.Exec("BEGIN");
for(Event& e : changes)
{
if (e.type == Event::Challenge && (e.action == Event::Added || e.action == Event::Updated))
{
ChallengeIndex* chal;
if (e.action == Event::Added)
{
chal = new ChallengeIndex();
chal->id = m_nextChalId++;
}
else
{
auto itChal = m_challenges.find(e.id);
assert(itChal != m_challenges.end());
chal = itChal->second;
}
if (e.json.is_discarded() || e.json.is_null())
{
Log("Tried to process invalid json in Challenge Add event", Logger::Severity::Warning);
continue;
}
chal->settings = e.json;
chal->settings["title"].get_to(chal->title);
chal->path = e.path;
chal->settings["level"].get_to(chal->level);
if (e.action == Event::Added)
{
chal->clearMark = 0;
chal->bestScore = 0;
}
chal->hash = e.hash;
chal->missingChart = false;
chal->lwt = e.lwt;
chal->charts.clear();
String chartMeta = "";
// Grab the charts
chal->FindCharts(&m_outer, chal->settings["charts"]);
chal->GenerateDescription();
String chartString = chal->settings["charts"].dump();
if (e.action == Event::Added)
{
m_challenges.Add(chal->id, chal);
// Add Chart
// ("title,charts,chart_meta,clear_mark,best_score,req_text,path,hash,level,lwt) "
addChallenge.BindString(1, chal->title);
addChallenge.BindString(2, chartString);
addChallenge.BindString(3, chartMeta);
addChallenge.BindInt(4, chal->clearMark);
addChallenge.BindInt(5, chal->bestScore);
addChallenge.BindString(6, chal->reqText);
addChallenge.BindString(7, chal->path);
addChallenge.BindString(8, chal->hash);
addChallenge.BindInt(9, chal->level);
addChallenge.BindInt64(10, chal->lwt);
addChallenge.Step();
addChallenge.Rewind();
addedChalEvents.Add(chal);
}
else if (e.action == Event::Updated)
{
updateChallenge.BindString(1, chal->title);
updateChallenge.BindString(2, chartString);
updateChallenge.BindString(3, chartMeta);
updateChallenge.BindInt(4, chal->clearMark);
updateChallenge.BindInt(5, chal->bestScore);
updateChallenge.BindString(6, chal->reqText);
updateChallenge.BindString(7, chal->path);
updateChallenge.BindString(8, chal->hash);
updateChallenge.BindInt(9, chal->level);
updateChallenge.BindInt64(10, chal->lwt);
updateChallenge.BindInt(11, e.id);
updateChallenge.Step();
updateChallenge.Rewind();
updatedChalEvents.Add(chal);
}
}
else if(e.type == Event::Challenge && e.action == Event::Removed)
{
auto itChal = m_challenges.find(e.id);
assert(itChal != m_challenges.end());
delete itChal->second;
m_challenges.erase(e.id);
// Remove diff in db
removeChallenge.BindInt(1, e.id);
removeChallenge.Step();
removeChallenge.Rewind();
}
if(e.type == Event::Chart && e.action == Event::Added)
{
String folderPath = Path::RemoveLast(e.path, nullptr);
bool existingUpdated;
FolderIndex* folder;
// Add or get folder
auto folderIt = m_foldersByPath.find(folderPath);
if(folderIt == m_foldersByPath.end())
{
// Add folder
folder = new FolderIndex();
folder->id = m_nextFolderId++;
folder->path = folderPath;
folder->selectId = (int32) m_folders.size();
m_folders.Add(folder->id, folder);
m_foldersByPath.Add(folder->path, folder);
addFolder.BindString(1, folder->path);
addFolder.BindInt(2, folder->id);
addFolder.Step();
addFolder.Rewind();
existingUpdated = false; // New folder
}
else
{
folder = folderIt->second;
existingUpdated = true; // Existing folder
}
ChartIndex* chart = new ChartIndex();
chart->id = m_nextChartId++;
chart->lwt = e.lwt;
chart->folderId = folder->id;
chart->path = e.path;
chart->title = e.mapData->title;
chart->artist = e.mapData->artist;
chart->level = e.mapData->level;
chart->effector = e.mapData->effector;
chart->preview_file = e.mapData->audioNoFX;