-
Notifications
You must be signed in to change notification settings - Fork 0
/
DataStore.java
3462 lines (3035 loc) · 138 KB
/
DataStore.java
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
package cgeo.geocaching.storage;
import cgeo.geocaching.CgeoApplication;
import cgeo.geocaching.Intents;
import cgeo.geocaching.R;
import cgeo.geocaching.SearchResult;
import cgeo.geocaching.connector.IConnector;
import cgeo.geocaching.connector.gc.Tile;
import cgeo.geocaching.enumerations.CacheSize;
import cgeo.geocaching.enumerations.CacheType;
import cgeo.geocaching.enumerations.LoadFlags;
import cgeo.geocaching.enumerations.LoadFlags.LoadFlag;
import cgeo.geocaching.enumerations.LoadFlags.RemoveFlag;
import cgeo.geocaching.enumerations.LoadFlags.SaveFlag;
import cgeo.geocaching.enumerations.LogType;
import cgeo.geocaching.enumerations.WaypointType;
import cgeo.geocaching.list.AbstractList;
import cgeo.geocaching.list.PseudoList;
import cgeo.geocaching.list.StoredList;
import cgeo.geocaching.location.Geopoint;
import cgeo.geocaching.location.Viewport;
import cgeo.geocaching.models.Destination;
import cgeo.geocaching.models.Geocache;
import cgeo.geocaching.models.Image;
import cgeo.geocaching.models.LogEntry;
import cgeo.geocaching.models.Trackable;
import cgeo.geocaching.models.Waypoint;
import cgeo.geocaching.search.SearchSuggestionCursor;
import cgeo.geocaching.settings.Settings;
import cgeo.geocaching.ui.dialog.Dialogs;
import cgeo.geocaching.utils.FileUtils;
import cgeo.geocaching.utils.Log;
import cgeo.geocaching.utils.Version;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.MatrixCursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteDoneException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import rx.Observable;
import rx.Observable.OnSubscribe;
import rx.Subscriber;
import rx.android.app.AppObservable;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func0;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
public class DataStore {
private DataStore() {
// utility class
}
public enum StorageLocation {
HEAP,
CACHE,
DATABASE,
}
private static final Func1<Cursor, String> GET_STRING_0 = new Func1<Cursor, String>() {
@Override
public String call(final Cursor cursor) {
return cursor.getString(0);
}
};
private static final Func1<Cursor, Integer> GET_INTEGER_0 = new Func1<Cursor, Integer>() {
@Override
public Integer call(final Cursor cursor) {
return cursor.getInt(0);
}
};
// Columns and indices for the cache data
private static final String QUERY_CACHE_DATA =
"SELECT " +
"cg_caches.updated," + // 0
"cg_caches.reason," + // 1
"cg_caches.detailed," + // 2
"cg_caches.detailedupdate," + // 3
"cg_caches.visiteddate," + // 4
"cg_caches.geocode," + // 5
"cg_caches.cacheid," + // 6
"cg_caches.guid," + // 7
"cg_caches.type," + // 8
"cg_caches.name," + // 9
"cg_caches.owner," + // 10
"cg_caches.owner_real," + // 11
"cg_caches.hidden," + // 12
"cg_caches.hint," + // 13
"cg_caches.size," + // 14
"cg_caches.difficulty," + // 15
"cg_caches.direction," + // 16
"cg_caches.distance," + // 17
"cg_caches.terrain," + // 18
"cg_caches.location," + // 19
"cg_caches.personal_note," + // 20
"cg_caches.shortdesc," + // 21
"cg_caches.favourite_cnt," + // 22
"cg_caches.rating," + // 23
"cg_caches.votes," + // 24
"cg_caches.myvote," + // 25
"cg_caches.disabled," + // 26
"cg_caches.archived," + // 27
"cg_caches.members," + // 28
"cg_caches.found," + // 29
"cg_caches.favourite," + // 30
"cg_caches.inventoryunknown," + // 31
"cg_caches.onWatchlist," + // 32
"cg_caches.reliable_latlon," + // 33
"cg_caches.coordsChanged," + // 34
"cg_caches.latitude," + // 35
"cg_caches.longitude," + // 36
"cg_caches.finalDefined," + // 37
"cg_caches._id," + // 38
"cg_caches.inventorycoins," + // 39
"cg_caches.inventorytags," + // 40
"cg_caches.logPasswordRequired," + // 41
"cg_caches.watchlistCount"; // 42
/** The list of fields needed for mapping. */
private static final String[] WAYPOINT_COLUMNS = { "_id", "geocode", "updated", "type", "prefix", "lookup", "name", "latitude", "longitude", "note", "own", "visited" };
/** Number of days (as ms) after temporarily saved caches are deleted */
private static final long DAYS_AFTER_CACHE_IS_DELETED = 3 * 24 * 60 * 60 * 1000;
/**
* holds the column indexes of the cache table to avoid lookups
*/
private static final CacheCache cacheCache = new CacheCache();
private static volatile SQLiteDatabase database = null;
private static final int dbVersion = 71;
public static final int customListIdOffset = 10;
@NonNull private static final String dbName = "data";
@NonNull private static final String dbTableCaches = "cg_caches";
@NonNull private static final String dbTableLists = "cg_lists";
@NonNull private static final String dbTableCachesLists = "cg_caches_lists";
@NonNull private static final String dbTableAttributes = "cg_attributes";
@NonNull private static final String dbTableWaypoints = "cg_waypoints";
@NonNull private static final String dbTableSpoilers = "cg_spoilers";
@NonNull private static final String dbTableLogs = "cg_logs";
@NonNull private static final String dbTableLogCount = "cg_logCount";
@NonNull private static final String dbTableLogImages = "cg_logImages";
@NonNull private static final String dbTableLogsOffline = "cg_logs_offline";
@NonNull private static final String dbTableTrackables = "cg_trackables";
@NonNull private static final String dbTableSearchDestinationHistory = "cg_search_destination_history";
@NonNull private static final String dbCreateCaches = ""
+ "create table " + dbTableCaches + " ("
+ "_id integer primary key autoincrement, "
+ "updated long not null, "
+ "detailed integer not null default 0, "
+ "detailedupdate long, "
+ "visiteddate long, "
+ "geocode text unique not null, "
+ "reason integer not null default 0, " // cached, favorite...
+ "cacheid text, "
+ "guid text, "
+ "type text, "
+ "name text, "
+ "owner text, "
+ "owner_real text, "
+ "hidden long, "
+ "hint text, "
+ "size text, "
+ "difficulty float, "
+ "terrain float, "
+ "location text, "
+ "direction double, "
+ "distance double, "
+ "latitude double, "
+ "longitude double, "
+ "reliable_latlon integer, "
+ "personal_note text, "
+ "shortdesc text, "
+ "description text, "
+ "favourite_cnt integer, "
+ "rating float, "
+ "votes integer, "
+ "myvote float, "
+ "disabled integer not null default 0, "
+ "archived integer not null default 0, "
+ "members integer not null default 0, "
+ "found integer not null default 0, "
+ "favourite integer not null default 0, "
+ "inventorycoins integer default 0, "
+ "inventorytags integer default 0, "
+ "inventoryunknown integer default 0, "
+ "onWatchlist integer default 0, "
+ "coordsChanged integer default 0, "
+ "finalDefined integer default 0, "
+ "logPasswordRequired integer default 0,"
+ "watchlistCount integer default -1"
+ "); ";
private static final String dbCreateLists = ""
+ "create table " + dbTableLists + " ("
+ "_id integer primary key autoincrement, "
+ "title text not null, "
+ "updated long not null"
+ "); ";
private static final String dbCreateCachesLists = ""
+ "create table " + dbTableCachesLists + " ("
+ "list_id integer not null, "
+ "geocode text not null, "
+ "primary key (list_id, geocode)"
+ "); ";
private static final String dbCreateAttributes = ""
+ "create table " + dbTableAttributes + " ("
+ "_id integer primary key autoincrement, "
+ "geocode text not null, "
+ "updated long not null, " // date of save
+ "attribute text "
+ "); ";
private static final String dbCreateWaypoints = ""
+ "create table " + dbTableWaypoints + " ("
+ "_id integer primary key autoincrement, "
+ "geocode text not null, "
+ "updated long not null, " // date of save
+ "type text not null default 'waypoint', "
+ "prefix text, "
+ "lookup text, "
+ "name text, "
+ "latitude double, "
+ "longitude double, "
+ "note text, "
+ "own integer default 0, "
+ "visited integer default 0"
+ "); ";
private static final String dbCreateSpoilers = ""
+ "create table " + dbTableSpoilers + " ("
+ "_id integer primary key autoincrement, "
+ "geocode text not null, "
+ "updated long not null, " // date of save
+ "url text, "
+ "title text, "
+ "description text "
+ "); ";
private static final String dbCreateLogs = ""
+ "create table " + dbTableLogs + " ("
+ "_id integer primary key autoincrement, "
+ "geocode text not null, "
+ "updated long not null, " // date of save
+ "type integer not null default 4, "
+ "author text, "
+ "log text, "
+ "date long, "
+ "found integer not null default 0, "
+ "friend integer "
+ "); ";
private static final String dbCreateLogCount = ""
+ "create table " + dbTableLogCount + " ("
+ "_id integer primary key autoincrement, "
+ "geocode text not null, "
+ "updated long not null, " // date of save
+ "type integer not null default 4, "
+ "count integer not null default 0 "
+ "); ";
private static final String dbCreateLogImages = ""
+ "create table " + dbTableLogImages + " ("
+ "_id integer primary key autoincrement, "
+ "log_id integer not null, "
+ "title text not null, "
+ "url text not null, "
+ "description text "
+ "); ";
private static final String dbCreateLogsOffline = ""
+ "create table " + dbTableLogsOffline + " ("
+ "_id integer primary key autoincrement, "
+ "geocode text not null, "
+ "updated long not null, " // date of save
+ "type integer not null default 4, "
+ "log text, "
+ "date long "
+ "); ";
private static final String dbCreateTrackables = ""
+ "create table " + dbTableTrackables + " ("
+ "_id integer primary key autoincrement, "
+ "updated long not null, " // date of save
+ "tbcode text not null, "
+ "guid text, "
+ "title text, "
+ "owner text, "
+ "released long, "
+ "goal text, "
+ "description text, "
+ "geocode text "
+ "); ";
private static final String dbCreateSearchDestinationHistory = ""
+ "create table " + dbTableSearchDestinationHistory + " ("
+ "_id integer primary key autoincrement, "
+ "date long not null, "
+ "latitude double, "
+ "longitude double "
+ "); ";
private static final Observable<Integer> allCachesCountObservable = Observable.create(new OnSubscribe<Integer>() {
@Override
public void call(final Subscriber<? super Integer> subscriber) {
if (isInitialized()) {
subscriber.onNext(getAllCachesCount());
subscriber.onCompleted();
}
}
}).timeout(500, TimeUnit.MILLISECONDS).retry(10).subscribeOn(Schedulers.io());
private static boolean newlyCreatedDatabase = false;
private static boolean databaseCleaned = false;
public static void init() {
if (database != null) {
return;
}
synchronized (DataStore.class) {
if (database != null) {
return;
}
final DbHelper dbHelper = new DbHelper(new DBContext(CgeoApplication.getInstance()));
try {
database = dbHelper.getWritableDatabase();
} catch (final Exception e) {
Log.e("DataStore.init: unable to open database for R/W", e);
recreateDatabase(dbHelper);
}
}
}
/**
* Attempt to recreate the database if opening has failed
*
* @param dbHelper dbHelper to use to reopen the database
*/
private static void recreateDatabase(final DbHelper dbHelper) {
final File dbPath = databasePath();
final File corruptedPath = new File(LocalStorage.getStorage(), dbPath.getName() + ".corrupted");
if (LocalStorage.copy(dbPath, corruptedPath)) {
Log.i("DataStore.init: renamed " + dbPath + " into " + corruptedPath);
} else {
Log.e("DataStore.init: unable to rename corrupted database");
}
try {
database = dbHelper.getWritableDatabase();
} catch (final Exception f) {
Log.e("DataStore.init: unable to recreate database and open it for R/W", f);
}
}
public static synchronized void closeDb() {
if (database == null) {
return;
}
cacheCache.removeAllFromCache();
PreparedStatement.clearPreparedStatements();
database.close();
database = null;
}
@NonNull
public static File getBackupFileInternal() {
return new File(LocalStorage.getStorage(), "cgeo.sqlite");
}
public static String backupDatabaseInternal() {
if (!LocalStorage.isExternalStorageAvailable()) {
Log.w("Database wasn't backed up: no external memory");
return null;
}
final File target = getBackupFileInternal();
closeDb();
final boolean backupDone = LocalStorage.copy(databasePath(), target);
init();
if (!backupDone) {
Log.e("Database could not be copied to " + target);
return null;
}
Log.i("Database was copied to " + target);
return target.getPath();
}
/**
* Move the database to/from external cgdata in a new thread,
* showing a progress window
*
*/
public static void moveDatabase(final Activity fromActivity) {
final ProgressDialog dialog = ProgressDialog.show(fromActivity, fromActivity.getString(R.string.init_dbmove_dbmove), fromActivity.getString(R.string.init_dbmove_running), true, false);
AppObservable.bindActivity(fromActivity, Observable.defer(new Func0<Observable<Boolean>>() {
@Override
public Observable<Boolean> call() {
if (!LocalStorage.isExternalStorageAvailable()) {
Log.w("Database was not moved: external memory not available");
return Observable.just(false);
}
closeDb();
final File source = databasePath();
final File target = databaseAlternatePath();
if (!LocalStorage.copy(source, target)) {
Log.e("Database could not be moved to " + target);
init();
return Observable.just(false);
}
if (!FileUtils.delete(source)) {
Log.e("Original database could not be deleted during move");
}
Settings.setDbOnSDCard(!Settings.isDbOnSDCard());
Log.i("Database was moved to " + target);
init();
return Observable.just(true);
}
})).subscribeOn(Schedulers.io()).subscribe(new Action1<Boolean>() {
@Override
public void call(final Boolean success) {
dialog.dismiss();
final String message = success ? fromActivity.getString(R.string.init_dbmove_success) : fromActivity.getString(R.string.init_dbmove_failed);
Dialogs.message(fromActivity, R.string.init_dbmove_dbmove, message);
}
});
}
@NonNull
private static File databasePath(final boolean internal) {
return new File(internal ? LocalStorage.getInternalDbDirectory() : LocalStorage.getExternalDbDirectory(), dbName);
}
@NonNull
private static File databasePath() {
return databasePath(!Settings.isDbOnSDCard());
}
@NonNull
private static File databaseAlternatePath() {
return databasePath(Settings.isDbOnSDCard());
}
public static boolean restoreDatabaseInternal() {
if (!LocalStorage.isExternalStorageAvailable()) {
Log.w("Database wasn't restored: no external memory");
return false;
}
final File sourceFile = getBackupFileInternal();
closeDb();
final boolean restoreDone = LocalStorage.copy(sourceFile, databasePath());
init();
if (restoreDone) {
Log.i("Database successfully restored from " + sourceFile.getPath());
} else {
Log.e("Could not restore database from " + sourceFile.getPath());
}
return restoreDone;
}
private static class DBContext extends ContextWrapper {
DBContext(final Context base) {
super(base);
}
/**
* We override the default open/create as it doesn't work on OS 1.6 and
* causes issues on other devices too.
*/
@Override
public SQLiteDatabase openOrCreateDatabase(final String name, final int mode,
final CursorFactory factory) {
final File file = new File(name);
FileUtils.mkdirs(file.getParentFile());
return SQLiteDatabase.openOrCreateDatabase(file, factory);
}
}
private static class DbHelper extends SQLiteOpenHelper {
private static boolean firstRun = true;
DbHelper(final Context context) {
super(context, databasePath().getPath(), null, dbVersion);
}
@Override
public void onCreate(final SQLiteDatabase db) {
newlyCreatedDatabase = true;
db.execSQL(dbCreateCaches);
db.execSQL(dbCreateLists);
db.execSQL(dbCreateCachesLists);
db.execSQL(dbCreateAttributes);
db.execSQL(dbCreateWaypoints);
db.execSQL(dbCreateSpoilers);
db.execSQL(dbCreateLogs);
db.execSQL(dbCreateLogCount);
db.execSQL(dbCreateLogImages);
db.execSQL(dbCreateLogsOffline);
db.execSQL(dbCreateTrackables);
db.execSQL(dbCreateSearchDestinationHistory);
createIndices(db);
}
private static void createIndices(final SQLiteDatabase db) {
db.execSQL("create index if not exists in_caches_geo on " + dbTableCaches + " (geocode)");
db.execSQL("create index if not exists in_caches_guid on " + dbTableCaches + " (guid)");
db.execSQL("create index if not exists in_caches_lat on " + dbTableCaches + " (latitude)");
db.execSQL("create index if not exists in_caches_lon on " + dbTableCaches + " (longitude)");
db.execSQL("create index if not exists in_caches_reason on " + dbTableCaches + " (reason)");
db.execSQL("create index if not exists in_caches_detailed on " + dbTableCaches + " (detailed)");
db.execSQL("create index if not exists in_caches_type on " + dbTableCaches + " (type)");
db.execSQL("create index if not exists in_caches_visit_detail on " + dbTableCaches + " (visiteddate, detailedupdate)");
db.execSQL("create index if not exists in_attr_geo on " + dbTableAttributes + " (geocode)");
db.execSQL("create index if not exists in_wpts_geo on " + dbTableWaypoints + " (geocode)");
db.execSQL("create index if not exists in_wpts_geo_type on " + dbTableWaypoints + " (geocode, type)");
db.execSQL("create index if not exists in_spoil_geo on " + dbTableSpoilers + " (geocode)");
db.execSQL("create index if not exists in_logs_geo on " + dbTableLogs + " (geocode)");
db.execSQL("create index if not exists in_logcount_geo on " + dbTableLogCount + " (geocode)");
db.execSQL("create index if not exists in_logsoff_geo on " + dbTableLogsOffline + " (geocode)");
db.execSQL("create index if not exists in_trck_geo on " + dbTableTrackables + " (geocode)");
db.execSQL("create index if not exists in_lists_geo on " + dbTableCachesLists + " (geocode)");
}
@Override
public void onUpgrade(final SQLiteDatabase db, final int oldVersion, final int newVersion) {
Log.i("Upgrade database from ver. " + oldVersion + " to ver. " + newVersion + ": start");
try {
if (db.isReadOnly()) {
return;
}
db.beginTransaction();
if (oldVersion <= 0) { // new table
dropDatabase(db);
onCreate(db);
Log.i("Database structure created.");
}
if (oldVersion > 0) {
db.execSQL("delete from " + dbTableCaches + " where reason = 0");
if (oldVersion < 52) { // upgrade to 52
try {
db.execSQL(dbCreateSearchDestinationHistory);
Log.i("Added table " + dbTableSearchDestinationHistory + ".");
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 52", e);
}
}
if (oldVersion < 53) { // upgrade to 53
try {
db.execSQL("alter table " + dbTableCaches + " add column onWatchlist integer");
Log.i("Column onWatchlist added to " + dbTableCaches + ".");
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 53", e);
}
}
if (oldVersion < 54) { // update to 54
try {
db.execSQL(dbCreateLogImages);
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 54", e);
}
}
if (oldVersion < 55) { // update to 55
try {
db.execSQL("alter table " + dbTableCaches + " add column personal_note text");
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 55", e);
}
}
// make all internal attribute names lowercase
// @see issue #299
if (oldVersion < 56) { // update to 56
try {
db.execSQL("update " + dbTableAttributes + " set attribute = " +
"lower(attribute) where attribute like \"%_yes\" " +
"or attribute like \"%_no\"");
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 56", e);
}
}
// Create missing indices. See issue #435
if (oldVersion < 57) { // update to 57
try {
db.execSQL("drop index in_a");
db.execSQL("drop index in_b");
db.execSQL("drop index in_c");
db.execSQL("drop index in_d");
db.execSQL("drop index in_e");
db.execSQL("drop index in_f");
createIndices(db);
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 57", e);
}
}
if (oldVersion < 58) { // upgrade to 58
try {
db.beginTransaction();
final String dbTableCachesTemp = dbTableCaches + "_temp";
final String dbCreateCachesTemp = ""
+ "create table " + dbTableCachesTemp + " ("
+ "_id integer primary key autoincrement, "
+ "updated long not null, "
+ "detailed integer not null default 0, "
+ "detailedupdate long, "
+ "visiteddate long, "
+ "geocode text unique not null, "
+ "reason integer not null default 0, "
+ "cacheid text, "
+ "guid text, "
+ "type text, "
+ "name text, "
+ "own integer not null default 0, "
+ "owner text, "
+ "owner_real text, "
+ "hidden long, "
+ "hint text, "
+ "size text, "
+ "difficulty float, "
+ "terrain float, "
+ "location text, "
+ "direction double, "
+ "distance double, "
+ "latitude double, "
+ "longitude double, "
+ "reliable_latlon integer, "
+ "personal_note text, "
+ "shortdesc text, "
+ "description text, "
+ "favourite_cnt integer, "
+ "rating float, "
+ "votes integer, "
+ "myvote float, "
+ "disabled integer not null default 0, "
+ "archived integer not null default 0, "
+ "members integer not null default 0, "
+ "found integer not null default 0, "
+ "favourite integer not null default 0, "
+ "inventorycoins integer default 0, "
+ "inventorytags integer default 0, "
+ "inventoryunknown integer default 0, "
+ "onWatchlist integer default 0 "
+ "); ";
db.execSQL(dbCreateCachesTemp);
db.execSQL("insert into " + dbTableCachesTemp + " select _id,updated,detailed,detailedupdate,visiteddate,geocode,reason,cacheid,guid,type,name,own,owner,owner_real," +
"hidden,hint,size,difficulty,terrain,location,direction,distance,latitude,longitude, 0," +
"personal_note,shortdesc,description,favourite_cnt,rating,votes,myvote,disabled,archived,members,found,favourite,inventorycoins," +
"inventorytags,inventoryunknown,onWatchlist from " + dbTableCaches);
db.execSQL("drop table " + dbTableCaches);
db.execSQL("alter table " + dbTableCachesTemp + " rename to " + dbTableCaches);
final String dbTableWaypointsTemp = dbTableWaypoints + "_temp";
final String dbCreateWaypointsTemp = ""
+ "create table " + dbTableWaypointsTemp + " ("
+ "_id integer primary key autoincrement, "
+ "geocode text not null, "
+ "updated long not null, " // date of save
+ "type text not null default 'waypoint', "
+ "prefix text, "
+ "lookup text, "
+ "name text, "
+ "latitude double, "
+ "longitude double, "
+ "note text "
+ "); ";
db.execSQL(dbCreateWaypointsTemp);
db.execSQL("insert into " + dbTableWaypointsTemp + " select _id, geocode, updated, type, prefix, lookup, name, latitude, longitude, note from " + dbTableWaypoints);
db.execSQL("drop table " + dbTableWaypoints);
db.execSQL("alter table " + dbTableWaypointsTemp + " rename to " + dbTableWaypoints);
createIndices(db);
db.setTransactionSuccessful();
Log.i("Removed latitude_string and longitude_string columns");
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 58", e);
} finally {
db.endTransaction();
}
}
if (oldVersion < 59) {
try {
// Add new indices and remove obsolete cache files
createIndices(db);
removeObsoleteCacheDirectories();
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 59", e);
}
}
if (oldVersion < 60) {
try {
removeSecEmptyDirs();
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 60", e);
}
}
if (oldVersion < 61) {
try {
db.execSQL("alter table " + dbTableLogs + " add column friend integer");
db.execSQL("alter table " + dbTableCaches + " add column coordsChanged integer default 0");
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 61", e);
}
}
// Introduces finalDefined on caches and own on waypoints
if (oldVersion < 62) {
try {
db.execSQL("alter table " + dbTableCaches + " add column finalDefined integer default 0");
db.execSQL("alter table " + dbTableWaypoints + " add column own integer default 0");
db.execSQL("update " + dbTableWaypoints + " set own = 1 where type = 'own'");
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 62", e);
}
}
if (oldVersion < 63) {
try {
removeDoubleUnderscoreMapFiles();
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 63", e);
}
}
if (oldVersion < 64) {
try {
// No cache should ever be stored into the ALL_CACHES list. Here we use hardcoded list ids
// rather than symbolic ones because the fix must be applied with the values at the time
// of the problem. The problem was introduced in release 2012.06.01.
db.execSQL("update " + dbTableCaches + " set reason=1 where reason=2");
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 64", e);
}
}
if (oldVersion < 65) {
try {
// Set all waypoints where name is Original coordinates to type ORIGINAL
db.execSQL("update " + dbTableWaypoints + " set type='original', own=0 where name='Original Coordinates'");
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 65:", e);
}
}
// Introduces visited feature on waypoints
if (oldVersion < 66) {
try {
db.execSQL("alter table " + dbTableWaypoints + " add column visited integer default 0");
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 66", e);
}
}
// issue2662 OC: Leichtes Klettern / Easy climbing
if (oldVersion < 67) {
try {
db.execSQL("update " + dbTableAttributes + " set attribute = 'easy_climbing_yes' where geocode like 'OC%' and attribute = 'climbing_yes'");
db.execSQL("update " + dbTableAttributes + " set attribute = 'easy_climbing_no' where geocode like 'OC%' and attribute = 'climbing_no'");
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 67", e);
}
}
// Introduces logPasswordRequired on caches
if (oldVersion < 68) {
try {
db.execSQL("alter table " + dbTableCaches + " add column logPasswordRequired integer default 0");
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 68", e);
}
}
// description for log Images
if (oldVersion < 69) {
try {
db.execSQL("alter table " + dbTableLogImages + " add column description text");
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 69", e);
}
}
// Introduces watchListCount
if (oldVersion < 70) {
try {
db.execSQL("alter table " + dbTableCaches + " add column watchlistCount integer default -1");
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 70", e);
}
}
// Introduces cachesLists
if (oldVersion < 71) {
try {
db.execSQL(dbCreateCachesLists);
createIndices(db);
db.execSQL("insert into " + dbTableCachesLists + " select reason, geocode from " + dbTableCaches);
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 71", e);
}
}
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
Log.i("Upgrade database from ver. " + oldVersion + " to ver. " + newVersion + ": completed");
}
@Override
public void onOpen(final SQLiteDatabase db) {
if (firstRun) {
sanityChecks(db);
firstRun = false;
}
}
/**
* Execute sanity checks that should be performed once per application after the database has been
* opened.
*
* @param db the database to perform sanity checks against
*/
private static void sanityChecks(final SQLiteDatabase db) {
// Check that the history of searches is well formed as some dates seem to be missing according
// to NPE traces.
final int staleHistorySearches = db.delete(dbTableSearchDestinationHistory, "date is null", null);
if (staleHistorySearches > 0) {
Log.w(String.format(Locale.getDefault(), "DataStore.dbHelper.onOpen: removed %d bad search history entries", staleHistorySearches));
}
}
/**
* Method to remove static map files with double underscore due to issue#1670
* introduced with release on 2012-05-24.
*/
private static void removeDoubleUnderscoreMapFiles() {
final File[] geocodeDirs = LocalStorage.getStorage().listFiles();
if (ArrayUtils.isNotEmpty(geocodeDirs)) {
final FilenameFilter filter = new FilenameFilter() {
@Override
public boolean accept(final File dir, final String filename) {
return filename.startsWith("map_") && filename.contains("__");
}
};
for (final File dir : geocodeDirs) {
final File[] wrongFiles = dir.listFiles(filter);
if (wrongFiles != null) {
for (final File wrongFile : wrongFiles) {
FileUtils.deleteIgnoringFailure(wrongFile);
}
}
}
}
}
/*
* Remove empty directories created in the secondary storage area.
*/
private static void removeSecEmptyDirs() {
final File[] files = LocalStorage.getStorageSec().listFiles();
if (ArrayUtils.isNotEmpty(files)) {
for (final File file : files) {
if (file.isDirectory()) {
// This will silently fail if the directory is not empty.
FileUtils.deleteIgnoringFailure(file);
}
}
}
}
private static void dropDatabase(final SQLiteDatabase db) {
db.execSQL("drop table if exists " + dbTableCachesLists);
db.execSQL("drop table if exists " + dbTableCaches);
db.execSQL("drop table if exists " + dbTableAttributes);
db.execSQL("drop table if exists " + dbTableWaypoints);
db.execSQL("drop table if exists " + dbTableSpoilers);
db.execSQL("drop table if exists " + dbTableLogs);
db.execSQL("drop table if exists " + dbTableLogCount);
db.execSQL("drop table if exists " + dbTableLogsOffline);
db.execSQL("drop table if exists " + dbTableTrackables);
}
}
/**
* Remove obsolete cache directories in c:geo private storage.
*/
public static void removeObsoleteCacheDirectories() {
final File[] files = LocalStorage.getStorage().listFiles();
if (ArrayUtils.isNotEmpty(files)) {
final Pattern oldFilePattern = Pattern.compile("^[GC|TB|EC|GK|O][A-Z0-9]{4,7}$");
final SQLiteStatement select = PreparedStatement.CHECK_IF_PRESENT.getStatement();
final List<File> toRemove = new ArrayList<>(files.length);
for (final File file : files) {
if (file.isDirectory()) {
final String geocode = file.getName();
if (oldFilePattern.matcher(geocode).find()) {
synchronized (select) {
select.bindString(1, geocode);
if (select.simpleQueryForLong() == 0) {
toRemove.add(file);
}
}
}
}
}
// Use a background thread for the real removal to avoid keeping the database locked
// if we are called from within a transaction.
Schedulers.io().createWorker().schedule(new Action0() {
@Override
public void call() {
for (final File dir : toRemove) {
Log.i("Removing obsolete cache directory for " + dir.getName());
FileUtils.deleteDirectory(dir);
}
}
});
}
}
public static boolean isThere(final String geocode, final String guid, final boolean checkTime) {
init();
long dataDetailedUpdate = 0;
int dataDetailed = 0;
try {
final Cursor cursor;
if (StringUtils.isNotBlank(geocode)) {
cursor = database.query(
dbTableCaches,
new String[]{"detailed", "detailedupdate", "updated"},
"geocode = ?",
new String[]{geocode},
null,