-
-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathBaseNoteDao.kt
More file actions
349 lines (279 loc) · 13.7 KB
/
BaseNoteDao.kt
File metadata and controls
349 lines (279 loc) · 13.7 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
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
package com.philkes.notallyx.data.dao
import android.content.ContextWrapper
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.RawQuery
import androidx.room.Update
import androidx.sqlite.db.SupportSQLiteQuery
import com.philkes.notallyx.R
import com.philkes.notallyx.data.model.Audio
import com.philkes.notallyx.data.model.BaseNote
import com.philkes.notallyx.data.model.FileAttachment
import com.philkes.notallyx.data.model.Folder
import com.philkes.notallyx.data.model.LabelsInBaseNote
import com.philkes.notallyx.data.model.ListItem
import com.philkes.notallyx.data.model.Reminder
import com.philkes.notallyx.data.model.Type
import com.philkes.notallyx.presentation.getQuantityString
import com.philkes.notallyx.presentation.showToast
import com.philkes.notallyx.utils.charLimit
import com.philkes.notallyx.utils.log
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
data class NoteIdReminder(val id: Long, val reminders: List<Reminder>)
data class NoteReminder(
val id: Long,
val title: String,
val type: Type,
val reminders: List<Reminder>,
)
/** Maximum allowed size of a note body in MB (~340,000 characters) */
const val MAX_BODY_SIZE_MB = 1.5
@Dao
interface BaseNoteDao {
@RawQuery fun query(query: SupportSQLiteQuery): Int
@Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insert(baseNote: BaseNote): Long
private fun BaseNote.truncated(): Pair<Boolean, BaseNote> {
return if (body.length > MAX_BODY_CHAR_LENGTH) {
return Pair(
true,
copy(
body = body.take(MAX_BODY_CHAR_LENGTH),
spans = spans.filter { it.isInsideBounds() },
),
)
} else Pair(false, this)
}
suspend fun insertSafe(context: ContextWrapper, baseNote: BaseNote): Long {
val (truncated, note) = baseNote.truncated()
if (truncated) {
context.log(
TAG,
"Note (id: ${note.id}, title: '${note.title}') is too big to insert. Truncating to ${note.body.length} characters (was: ${baseNote.body.length})",
)
context.showToast(
context.getString(
R.string.note_too_big_truncating,
note.body.length,
baseNote.body.length,
)
)
}
return insert(note)
}
suspend fun insertSafe(context: ContextWrapper, baseNotes: List<BaseNote>): List<Long> {
val truncatedNotes = mutableListOf<BaseNote>()
var truncatedCharacterSize = 0
val notes =
baseNotes.map { baseNote ->
val (truncated, note) = baseNote.truncated()
if (truncated) {
truncatedCharacterSize += baseNote.body.length
truncatedNotes.add(note)
}
note
}
if (truncatedNotes.isNotEmpty()) {
context.log(
TAG,
"${truncatedNotes.size} Notes are too big to save, they were truncated to $truncatedCharacterSize characters",
)
context.showToast(
context.getQuantityString(
R.plurals.notes_too_big_truncating,
truncatedNotes.size,
truncatedCharacterSize,
)
)
}
return insert(notes)
}
@Insert suspend fun insert(baseNotes: List<BaseNote>): List<Long>
@Update(entity = BaseNote::class) suspend fun update(labelsInBaseNotes: List<LabelsInBaseNote>)
@Query("SELECT COUNT(*) FROM BaseNote") fun count(): Int
@Query("DELETE FROM BaseNote") suspend fun deleteAll()
@Query("DELETE FROM BaseNote WHERE id = :id") suspend fun delete(id: Long)
@Query("DELETE FROM BaseNote WHERE id IN (:ids)") suspend fun delete(ids: LongArray)
@Query("DELETE FROM BaseNote WHERE folder = :folder") suspend fun deleteFrom(folder: Folder)
@Query("SELECT * FROM BaseNote WHERE folder = :folder ORDER BY pinned DESC, timestamp DESC")
fun getFrom(folder: Folder): LiveData<List<BaseNote>>
@Query("SELECT * FROM BaseNote WHERE folder = 'NOTES' ORDER BY pinned DESC, timestamp DESC")
suspend fun getAllNotes(): List<BaseNote>
@Query("SELECT * FROM BaseNote") fun getAllAsync(): LiveData<List<BaseNote>>
@Query("SELECT * FROM BaseNote") fun getAll(): List<BaseNote>
@Query("SELECT * FROM BaseNote WHERE id IN (:ids)") fun getByIds(ids: LongArray): List<BaseNote>
@Query("SELECT B.id FROM BaseNote B") fun getAllIds(): List<Long>
@Query("SELECT * FROM BaseNote WHERE id = :id") fun get(id: Long): BaseNote?
@Query("SELECT * FROM BaseNote WHERE title = :title")
fun getByTitle(title: String): List<BaseNote>
@Query("SELECT images FROM BaseNote WHERE id = :id") fun getImages(id: Long): String
@Query("SELECT images FROM BaseNote WHERE id IN (:ids)")
fun getImages(ids: LongArray): List<String>
@Query("SELECT files FROM BaseNote WHERE id IN (:ids)")
fun getFiles(ids: LongArray): List<String>
@Query("SELECT audios FROM BaseNote WHERE id IN (:ids)")
fun getAudios(ids: LongArray): List<String>
@Query("SELECT images FROM BaseNote") fun getAllImages(): List<String>
@Query("SELECT files FROM BaseNote") fun getAllFiles(): List<String>
@Query("SELECT audios FROM BaseNote") fun getAllAudios(): List<String>
@Query("SELECT id, reminders FROM BaseNote WHERE reminders IS NOT NULL AND reminders != '[]'")
suspend fun getAllReminders(): List<NoteIdReminder>
@Query("SELECT color FROM BaseNote WHERE id = :id ") fun getColorOfNote(id: Long): String?
@Query(
"SELECT id, title, type, reminders FROM BaseNote WHERE reminders IS NOT NULL AND reminders != '[]'"
)
fun getAllRemindersAsync(): LiveData<List<NoteReminder>>
@Query("SELECT * FROM BaseNote WHERE reminders IS NOT NULL AND reminders != '[]'")
fun getAllBaseNotesWithReminders(): LiveData<List<BaseNote>>
@Query("SELECT id FROM BaseNote WHERE folder = 'DELETED'")
suspend fun getDeletedNoteIds(): LongArray
@Query("SELECT id FROM BaseNote WHERE folder = 'DELETED' AND modifiedTimestamp < :before")
suspend fun getDeletedNoteIdsOlderThan(before: Long): LongArray
@Query("SELECT images FROM BaseNote WHERE folder = 'DELETED'")
suspend fun getDeletedNoteImages(): List<String>
@Query("SELECT files FROM BaseNote WHERE folder = 'DELETED'")
suspend fun getDeletedNoteFiles(): List<String>
@Query("SELECT audios FROM BaseNote WHERE folder = 'DELETED'")
suspend fun getDeletedNoteAudios(): List<String>
@Query("UPDATE BaseNote SET folder = :folder WHERE id IN (:ids)")
suspend fun move(ids: LongArray, folder: Folder)
@Query(
"UPDATE BaseNote SET folder = :folder, modifiedTimestamp = :timestamp WHERE id IN (:ids)"
)
suspend fun move(ids: LongArray, folder: Folder, timestamp: Long)
@Query("SELECT DISTINCT color FROM BaseNote") suspend fun getAllColors(): List<String>
@Query("UPDATE BaseNote SET color = :color WHERE id IN (:ids)")
suspend fun updateColor(ids: LongArray, color: String)
@Query("UPDATE BaseNote SET color = :newColor WHERE color = :oldColor")
suspend fun updateColor(oldColor: String, newColor: String)
@Query("UPDATE BaseNote SET pinned = :pinned WHERE id IN (:ids)")
suspend fun updatePinned(ids: LongArray, pinned: Boolean)
@Query("UPDATE BaseNote SET labels = :labels WHERE id = :id")
suspend fun updateLabels(id: Long, labels: List<String>)
@Query("UPDATE BaseNote SET labels = :labels WHERE id IN (:ids)")
suspend fun updateLabels(ids: LongArray, labels: List<String>)
@Query("UPDATE BaseNote SET items = :items WHERE id = :id")
suspend fun updateItems(id: Long, items: List<ListItem>)
@Query("UPDATE BaseNote SET images = :images WHERE id = :id")
suspend fun updateImages(id: Long, images: List<FileAttachment>)
@Query("UPDATE BaseNote SET files = :files WHERE id = :id")
suspend fun updateFiles(id: Long, files: List<FileAttachment>)
@Query("UPDATE BaseNote SET audios = :audios WHERE id = :id")
suspend fun updateAudios(id: Long, audios: List<Audio>)
@Query("UPDATE BaseNote SET reminders = :reminders WHERE id = :id")
suspend fun updateReminders(id: Long, reminders: List<Reminder>)
@Query("UPDATE BaseNote SET spans = :spans WHERE id = :id")
suspend fun updateSpans(
id: Long,
spans: List<com.philkes.notallyx.data.model.SpanRepresentation>,
)
// Truncate body at DB level without loading the row, to resolve oversized rows safely
@Query("UPDATE BaseNote SET body = substr(body, 1, :limit) WHERE id = :id")
suspend fun truncateBody(id: Long, limit: Int)
/**
* Both id and position can be invalid.
*
* Example of id being invalid - User adds a widget, then goes to Settings and clears app data.
* Now the widget refers to a list which doesn't exist.
*
* Example of position being invalid - User adds a widget, goes to Settings, clears app data and
* then imports a backup. Even if the backup contains the same list and it is inserted with the
* same id, it may not be of the safe size.
*
* In this case, an exception will be thrown. It is the caller's responsibility to handle it.
*/
suspend fun updateChecked(id: Long, position: Int, checked: Boolean) {
val items =
requireNotNull(get(id), { "updateChecked: Note with id '$id' does not exist" }).items
items[position].checked = checked
updateItems(id, items)
}
/** see [updateChecked] */
suspend fun updateChecked(id: Long, positions: List<Int>, checked: Boolean) {
val items =
requireNotNull(get(id), { "updateChecked: Note with id '$id' does not exist" }).items
positions.forEach { position -> items[position].checked = checked }
updateItems(id, items)
}
/**
* Since we store the labels as a JSON Array, it is not possible to perform operations on it.
* Thus, we use the 'Like' query which can return false positives sometimes.
*
* For example, a request for all base notes having the label 'Important' will also return base
* notes with the label 'Unimportant'. To prevent this, we use the extension function `map`
* directly on the LiveData to filter the results accordingly.
*/
fun getBaseNotesByLabel(label: String): Flow<List<BaseNote>> {
val result = getBaseNotesByLabel(label, setOf(Folder.NOTES, Folder.ARCHIVED))
return result.map { list -> list.filter { baseNote -> baseNote.labels.contains(label) } }
}
@Query(
"SELECT * FROM BaseNote WHERE folder IN (:folders) AND labels LIKE '%' || :label || '%' ORDER BY folder DESC, pinned DESC, timestamp DESC"
)
fun getBaseNotesByLabel(label: String, folders: Collection<Folder>): Flow<List<BaseNote>>
@Query(
"SELECT * FROM BaseNote WHERE folder = :folder AND labels == '[]' ORDER BY pinned DESC, timestamp DESC"
)
fun getBaseNotesWithoutLabel(folder: Folder): Flow<List<BaseNote>>
suspend fun getListOfBaseNotesByLabel(label: String): List<BaseNote> {
val result = getListOfBaseNotesByLabelImpl(label)
return result.filter { baseNote -> baseNote.labels.contains(label) }
}
@Query("SELECT * FROM BaseNote WHERE labels LIKE '%' || :label || '%'")
suspend fun getListOfBaseNotesByLabelImpl(label: String): List<BaseNote>
fun getBaseNotesByKeyword(
keyword: String,
folder: Folder,
label: String?,
): Flow<List<BaseNote>> {
val result =
when (label) {
null -> getBaseNotesByKeywordUnlabeledImpl(keyword, folder)
"" -> getBaseNotesByKeywordImpl(keyword, folder)
else -> getBaseNotesByKeywordImpl(keyword, folder, label)
}
return result.map { list -> list.filter { baseNote -> matchesKeyword(baseNote, keyword) } }
}
@Query(
"SELECT * FROM BaseNote WHERE folder = :folder AND labels LIKE '%' || :label || '%' AND (title LIKE '%' || :keyword || '%' OR body LIKE '%' || :keyword || '%' OR items LIKE '%' || :keyword || '%') ORDER BY pinned DESC, timestamp DESC"
)
fun getBaseNotesByKeywordImpl(
keyword: String,
folder: Folder,
label: String,
): Flow<List<BaseNote>>
@Query(
"SELECT * FROM BaseNote WHERE folder = :folder AND (title LIKE '%' || :keyword || '%' OR body LIKE '%' || :keyword || '%' OR items LIKE '%' || :keyword || '%' OR labels LIKE '%' || :keyword || '%') ORDER BY pinned DESC, timestamp DESC"
)
fun getBaseNotesByKeywordImpl(keyword: String, folder: Folder): Flow<List<BaseNote>>
@Query(
"SELECT * FROM BaseNote WHERE folder = :folder AND labels == '[]' AND (title LIKE '%' || :keyword || '%' OR body LIKE '%' || :keyword || '%' OR items LIKE '%' || :keyword || '%') ORDER BY pinned DESC, timestamp DESC"
)
fun getBaseNotesByKeywordUnlabeledImpl(keyword: String, folder: Folder): Flow<List<BaseNote>>
private fun matchesKeyword(baseNote: BaseNote, keyword: String): Boolean {
if (baseNote.title.contains(keyword, true)) {
return true
}
if (baseNote.body.contains(keyword, true)) {
return true
}
for (label in baseNote.labels) {
if (label.contains(keyword, true)) {
return true
}
}
for (item in baseNote.items) {
if (item.body.contains(keyword, true)) {
return true
}
}
return false
}
companion object {
private const val TAG = "BaseNoteDao"
val MAX_BODY_CHAR_LENGTH = MAX_BODY_SIZE_MB.charLimit()
}
}