-
-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathNotallyDatabase.kt
More file actions
320 lines (280 loc) · 12.6 KB
/
Copy pathNotallyDatabase.kt
File metadata and controls
320 lines (280 loc) · 12.6 KB
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
package com.philkes.notallyx.data
import android.content.Context
import android.content.ContextWrapper
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.lifecycle.Observer
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import androidx.room.migration.Migration
import androidx.sqlite.db.SimpleSQLiteQuery
import androidx.sqlite.db.SupportSQLiteDatabase
import com.philkes.notallyx.NotallyXApplication.Companion.isTestRunner
import com.philkes.notallyx.data.dao.BaseNoteDao
import com.philkes.notallyx.data.dao.CommonDao
import com.philkes.notallyx.data.dao.LabelDao
import com.philkes.notallyx.data.model.BaseNote
import com.philkes.notallyx.data.model.Color
import com.philkes.notallyx.data.model.Converters
import com.philkes.notallyx.data.model.Label
import com.philkes.notallyx.data.model.NoteViewMode
import com.philkes.notallyx.data.model.toColorString
import com.philkes.notallyx.presentation.view.misc.NotNullLiveData
import com.philkes.notallyx.presentation.viewmodel.preference.BiometricLock
import com.philkes.notallyx.presentation.viewmodel.preference.NotallyXPreferences
import com.philkes.notallyx.presentation.viewmodel.preference.observeForeverSkipFirst
import com.philkes.notallyx.utils.getExternalMediaDirectory
import com.philkes.notallyx.utils.security.SQLCipherUtils
import com.philkes.notallyx.utils.security.getInitializedCipherForDecryption
import java.io.File
import net.zetetic.database.sqlcipher.SupportOpenHelperFactory
@TypeConverters(Converters::class)
@Database(entities = [BaseNote::class, Label::class], version = 10)
abstract class NotallyDatabase : RoomDatabase() {
abstract fun getLabelDao(): LabelDao
abstract fun getCommonDao(): CommonDao
abstract fun getBaseNoteDao(): BaseNoteDao
fun checkpoint() {
getBaseNoteDao().query(SimpleSQLiteQuery("pragma wal_checkpoint(FULL)"))
}
fun ping() = getBaseNoteDao().query(SimpleSQLiteQuery("SELECT 1")) == 1
private var biometricLockObserver: Observer<BiometricLock>? = null
private var dataInPublicFolderObserver: Observer<Boolean>? = null
companion object {
const val DATABASE_NAME = "NotallyDatabase"
@Volatile private var instance: NotNullLiveData<NotallyDatabase>? = null
fun getCurrentDatabaseFile(context: ContextWrapper): File {
return if (NotallyXPreferences.getInstance(context).dataInPublicFolder.value) {
getExternalDatabaseFile(context)
} else {
getInternalDatabaseFile(context)
}
}
fun getExternalDatabaseFile(context: ContextWrapper): File {
return File(context.getExternalMediaDirectory(), DATABASE_NAME)
}
fun getExternalDatabaseFiles(context: ContextWrapper): List<File> {
return listOf(
File(context.getExternalMediaDirectory(), DATABASE_NAME),
File(context.getExternalMediaDirectory(), "$DATABASE_NAME-shm"),
File(context.getExternalMediaDirectory(), "$DATABASE_NAME-wal"),
)
}
fun getInternalDatabaseFile(context: Context): File {
return context.getDatabasePath(DATABASE_NAME)
}
fun getInternalDatabaseFiles(context: ContextWrapper): List<File> {
val directory = context.getDatabasePath(DATABASE_NAME).parentFile
return listOf(
File(directory, DATABASE_NAME),
File(directory, "$DATABASE_NAME-shm"),
File(directory, "$DATABASE_NAME-wal"),
)
}
private fun getCurrentDatabaseName(
context: ContextWrapper,
dataInPublicFolder: Boolean,
): String {
return if (dataInPublicFolder) {
getExternalDatabaseFile(context).absolutePath
} else {
DATABASE_NAME
}
}
fun getDatabase(
context: ContextWrapper,
observePreferences: Boolean = true,
): NotNullLiveData<NotallyDatabase> {
return instance
?: synchronized(this) {
val preferences = NotallyXPreferences.getInstance(context)
this.instance =
NotNullLiveData(createInstance(context, preferences, observePreferences))
return this.instance!!
}
}
private var testInstance: NotallyDatabase? = null
private fun getTestDatabase(context: ContextWrapper): NotallyDatabase {
return testInstance
?: synchronized(this) {
testInstance =
Room.inMemoryDatabaseBuilder(context, NotallyDatabase::class.java)
.allowMainThreadQueries()
.build()
return testInstance!!
}
}
fun getFreshDatabase(context: ContextWrapper, dataInPublic: Boolean): NotallyDatabase {
return if (isTestRunner()) {
getTestDatabase(context)
} else {
createInstance(
context,
NotallyXPreferences.getInstance(context),
false,
dataInPublic = dataInPublic,
)
}
}
private fun createInstance(
context: ContextWrapper,
preferences: NotallyXPreferences,
observePreferences: Boolean,
dataInPublic: Boolean = preferences.dataInPublicFolder.value,
): NotallyDatabase {
val instanceBuilder =
Room.databaseBuilder(
context,
NotallyDatabase::class.java,
getCurrentDatabaseName(context, dataInPublic),
)
.addMigrations(
Migration2,
Migration3,
Migration4,
Migration5,
Migration6,
Migration7,
Migration8,
Migration9,
Migration10,
)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
System.loadLibrary("sqlcipher")
if (preferences.isLockEnabled) {
if (
SQLCipherUtils.getDatabaseState(getCurrentDatabaseFile(context)) ==
SQLCipherUtils.State.ENCRYPTED
) {
initializeDecryption(preferences, instanceBuilder)
} else {
preferences.biometricLock.save(BiometricLock.DISABLED)
}
} else {
if (
SQLCipherUtils.getDatabaseState(getCurrentDatabaseFile(context)) ==
SQLCipherUtils.State.ENCRYPTED
) {
preferences.biometricLock.save(BiometricLock.ENABLED)
initializeDecryption(preferences, instanceBuilder)
}
}
val instance = instanceBuilder.build()
if (observePreferences) {
instance.biometricLockObserver = Observer {
NotallyDatabase.instance?.value?.biometricLockObserver?.let {
preferences.biometricLock.removeObserver(it)
}
val newInstance = createInstance(context, preferences, true)
NotallyDatabase.instance?.postValue(newInstance)
preferences.biometricLock.observeForeverSkipFirst(
newInstance.biometricLockObserver!!
)
}
preferences.biometricLock.observeForeverSkipFirst(
instance.biometricLockObserver!!
)
instance.dataInPublicFolderObserver = Observer {
NotallyDatabase.instance?.value?.dataInPublicFolderObserver?.let {
preferences.dataInPublicFolder.removeObserver(it)
}
val newInstance = createInstance(context, preferences, true)
NotallyDatabase.instance?.postValue(newInstance)
preferences.dataInPublicFolder.observeForeverSkipFirst(
newInstance.dataInPublicFolderObserver!!
)
}
preferences.dataInPublicFolder.observeForeverSkipFirst(
instance.dataInPublicFolderObserver!!
)
}
return instance
}
return instanceBuilder.build()
}
@RequiresApi(Build.VERSION_CODES.M)
private fun initializeDecryption(
preferences: NotallyXPreferences,
instanceBuilder: Builder<NotallyDatabase>,
) {
val initializationVector = preferences.iv.value!!
val cipher = getInitializedCipherForDecryption(iv = initializationVector)
val encryptedPassphrase = preferences.databaseEncryptionKey.value
val passphrase = cipher.doFinal(encryptedPassphrase)
val factory = SupportOpenHelperFactory(passphrase)
instanceBuilder.openHelperFactory(factory)
}
object Migration2 : Migration(1, 2) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL(
"ALTER TABLE `BaseNote` ADD COLUMN `color` TEXT NOT NULL DEFAULT 'DEFAULT'"
)
}
}
object Migration3 : Migration(2, 3) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE `BaseNote` ADD COLUMN `images` TEXT NOT NULL DEFAULT `[]`")
}
}
object Migration4 : Migration(3, 4) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE `BaseNote` ADD COLUMN `audios` TEXT NOT NULL DEFAULT `[]`")
}
}
object Migration5 : Migration(4, 5) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE `BaseNote` ADD COLUMN `files` TEXT NOT NULL DEFAULT `[]`")
}
}
object Migration6 : Migration(5, 6) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL(
"ALTER TABLE `BaseNote` ADD COLUMN `modifiedTimestamp` INTEGER NOT NULL DEFAULT 'timestamp'"
)
}
}
object Migration7 : Migration(6, 7) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL(
"ALTER TABLE `BaseNote` ADD COLUMN `reminders` TEXT NOT NULL DEFAULT `[]`"
)
}
}
object Migration8 : Migration(7, 8) {
override fun migrate(db: SupportSQLiteDatabase) {
val cursor = db.query("SELECT id, color FROM BaseNote")
while (cursor.moveToNext()) {
val id = cursor.getLong(cursor.getColumnIndexOrThrow("id"))
val colorString = cursor.getString(cursor.getColumnIndexOrThrow("color"))
val color = Color.valueOfOrDefault(colorString)
val hexColor = color.toColorString()
db.execSQL("UPDATE BaseNote SET color = ? WHERE id = ?", arrayOf(hexColor, id))
}
cursor.close()
}
}
object Migration9 : Migration(8, 9) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL(
"ALTER TABLE `BaseNote` ADD COLUMN `viewMode` TEXT NOT NULL DEFAULT '${NoteViewMode.EDIT.name}'"
)
}
}
object Migration10 : Migration(9, 10) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE `BaseNote` ADD COLUMN `sortIdx` INTEGER")
db.execSQL(
"CREATE INDEX IF NOT EXISTS `index_BaseNote_sortIdx` ON `BaseNote` (`sortIdx`)"
)
db.execSQL(
"DROP INDEX IF EXISTS `index_BaseNote_id_folder_pinned_timestamp_labels_sortIdx` "
)
db.execSQL(
"CREATE INDEX IF NOT EXISTS `index_BaseNote_id_folder_pinned_timestamp_labels` ON `BaseNote` (`id`, `folder`, `pinned`, `timestamp`, `labels`)"
)
}
}
}
}