-
-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathNotallyModel.kt
More file actions
496 lines (432 loc) · 17.3 KB
/
NotallyModel.kt
File metadata and controls
496 lines (432 loc) · 17.3 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
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
package com.philkes.notallyx.presentation.viewmodel
import android.app.Application
import android.graphics.Typeface
import android.net.Uri
import android.text.Editable
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.style.CharacterStyle
import android.text.style.StrikethroughSpan
import android.text.style.StyleSpan
import android.text.style.TypefaceSpan
import android.text.style.URLSpan
import androidx.core.text.getSpans
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.philkes.notallyx.R
import com.philkes.notallyx.data.NotallyDatabase
import com.philkes.notallyx.data.dao.BaseNoteDao
import com.philkes.notallyx.data.dao.NoteIdReminder
import com.philkes.notallyx.data.imports.txt.extractListItems
import com.philkes.notallyx.data.imports.txt.findListSyntaxRegex
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.ListItem
import com.philkes.notallyx.data.model.NoteViewMode
import com.philkes.notallyx.data.model.Reminder
import com.philkes.notallyx.data.model.SpanRepresentation
import com.philkes.notallyx.data.model.Type
import com.philkes.notallyx.data.model.attachmentsDifferFrom
import com.philkes.notallyx.data.model.copy
import com.philkes.notallyx.data.model.deepCopy
import com.philkes.notallyx.presentation.activity.note.reminders.RemindersActivity.Companion.NEW_REMINDER_ID
import com.philkes.notallyx.presentation.applySpans
import com.philkes.notallyx.presentation.showToast
import com.philkes.notallyx.presentation.view.misc.NotNullLiveData
import com.philkes.notallyx.presentation.view.misc.Progress
import com.philkes.notallyx.presentation.viewmodel.preference.NotallyXPreferences
import com.philkes.notallyx.presentation.viewmodel.preference.TextSizeSp
import com.philkes.notallyx.presentation.viewmodel.progress.AddFilesProgress
import com.philkes.notallyx.presentation.widget.WidgetProvider
import com.philkes.notallyx.utils.Cache
import com.philkes.notallyx.utils.Event
import com.philkes.notallyx.utils.FileError
import com.philkes.notallyx.utils.backup.checkBackupOnSave
import com.philkes.notallyx.utils.backup.importAudio
import com.philkes.notallyx.utils.backup.importFile
import com.philkes.notallyx.utils.cancelNoteReminders
import com.philkes.notallyx.utils.cancelReminder
import com.philkes.notallyx.utils.deleteAttachments
import com.philkes.notallyx.utils.getCurrentAudioDirectory
import com.philkes.notallyx.utils.getCurrentFilesDirectory
import com.philkes.notallyx.utils.getCurrentImagesDirectory
import com.philkes.notallyx.utils.getTempAudioFile
import com.philkes.notallyx.utils.scheduleReminder
import java.io.File
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
typealias BackupFile = Pair<String?, File>
class NotallyModel(private val app: Application) : AndroidViewModel(app) {
private val database = NotallyDatabase.getDatabase(app)
private lateinit var baseNoteDao: BaseNoteDao
val preferences = NotallyXPreferences.getInstance(app)
val textSize: TextSizeSp = preferences.textSizeNoteEditor.value
var isNewNote = true
var type = Type.NOTE
var id = 0L
var folder = Folder.NOTES
var color = preferences.defaultNoteColor.value
var title = String()
var pinned = false
var timestamp = System.currentTimeMillis()
var modifiedTimestamp = System.currentTimeMillis()
val labels = ArrayList<String>()
var body: Editable = SpannableStringBuilder()
val items = ArrayList<ListItem>()
val images = NotNullLiveData<List<FileAttachment>>(emptyList())
val files = NotNullLiveData<List<FileAttachment>>(emptyList())
val audios = NotNullLiveData<List<Audio>>(emptyList())
val reminders = NotNullLiveData<List<Reminder>>(emptyList())
val viewMode = NotNullLiveData(NoteViewMode.EDIT)
val addingFiles = MutableLiveData<Progress>()
val eventBus = MutableLiveData<Event<List<FileError>>>()
var imageRoot = app.getCurrentImagesDirectory()
var audioRoot = app.getCurrentAudioDirectory()
var filesRoot = app.getCurrentFilesDirectory()
var originalNote: BaseNote? = null
init {
database.observeForever { baseNoteDao = it.getBaseNoteDao() }
}
fun addAudio() {
viewModelScope.launch {
val audio = app.importAudio(app.getTempAudioFile(), true)
val copy = ArrayList(audios.value)
copy.add(audio)
audios.value = copy
updateAudios()
}
}
fun deleteAudio(audio: Audio) {
viewModelScope.launch {
val copy = ArrayList(audios.value)
copy.remove(audio)
audios.value = copy
updateAudios()
withContext(Dispatchers.IO) { app.deleteAttachments(arrayListOf(audio)) }
}
}
fun addImages(uris: Array<Uri>) {
/*
Regenerate because the directory may have been deleted between the time of activity creation
and image addition
*/
imageRoot = app.getCurrentImagesDirectory()
requireNotNull(imageRoot) { "imageRoot is null" }
addFiles(uris, imageRoot!!, FileType.IMAGE)
}
fun addFiles(uris: Array<Uri>) {
/*
Regenerate because the directory may have been deleted between the time of activity creation
and image addition
*/
filesRoot = app.getCurrentFilesDirectory()
requireNotNull(filesRoot) { "filesRoot is null" }
addFiles(uris, filesRoot!!, FileType.ANY)
}
private fun addFiles(uris: Array<Uri>, directory: File, fileType: FileType) {
val errorWhileRenaming =
if (fileType == FileType.IMAGE) {
R.string.error_while_renaming_image
} else {
R.string.error_while_renaming_file
}
viewModelScope.launch {
addingFiles.postValue(AddFilesProgress(0, uris.size))
val successes = ArrayList<FileAttachment>()
val errors = ArrayList<FileError>()
uris.forEachIndexed { index, uri ->
val (fileAttachment, error) =
app.importFile(uri, directory, fileType, errorWhileRenaming)
fileAttachment?.let { successes.add(it) }
error?.let { errors.add(it) }
addingFiles.postValue(AddFilesProgress(index + 1, uris.size))
}
addingFiles.postValue(AddFilesProgress(inProgress = false))
if (successes.isNotEmpty()) {
val copy =
when (fileType) {
FileType.IMAGE -> ArrayList(images.value)
FileType.ANY -> ArrayList(files.value)
}
copy.addAll(successes)
when (fileType) {
FileType.IMAGE -> {
images.value = copy
updateImages()
}
FileType.ANY -> {
files.value = copy
updateFiles()
}
}
}
if (errors.isNotEmpty()) {
eventBus.value = Event(errors)
}
}
}
fun deleteImages(list: ArrayList<FileAttachment>) {
viewModelScope.launch {
val copy = ArrayList(images.value)
copy.removeAll(list)
images.value = copy
updateImages()
withContext(Dispatchers.IO) { app.deleteAttachments(list) }
}
}
fun deleteFiles(list: ArrayList<FileAttachment>) {
viewModelScope.launch {
val copy = ArrayList(files.value)
copy.removeAll(list)
files.value = copy
updateFiles()
withContext(Dispatchers.IO) { app.deleteAttachments(list) }
}
}
fun setLabels(list: List<String>) {
labels.clear()
labels.addAll(list)
}
suspend fun setState(id: Long, createInDb: Boolean = true) {
if (id != 0L) {
isNewNote = false
val cachedNote = Cache.list.find { baseNote -> baseNote.id == id }
val baseNote = cachedNote ?: withContext(Dispatchers.IO) { baseNoteDao.get(id) }
if (baseNote != null) {
originalNote = baseNote.deepCopy()
this.id = id
folder = baseNote.folder
color = baseNote.color
title = baseNote.title
pinned = baseNote.pinned
timestamp = baseNote.timestamp
modifiedTimestamp = baseNote.modifiedTimestamp
setLabels(baseNote.labels)
body = baseNote.body.applySpans(baseNote.spans)
items.clear()
items.addAll(baseNote.items)
images.value = baseNote.images
files.value = baseNote.files
audios.value = baseNote.audios
reminders.value = baseNote.reminders
viewMode.value = baseNote.viewMode
} else {
originalNote = createBaseNote(createInDb)
app.showToast(R.string.cant_find_note)
}
} else originalNote = createBaseNote(createInDb)
}
private suspend fun createBaseNote(createInDb: Boolean = true): BaseNote {
val baseNote = getBaseNote()
if (createInDb) {
id = withContext(Dispatchers.IO) { baseNoteDao.insertSafe(app, baseNote) }
}
return baseNote.copy(id = id)
}
suspend fun deleteBaseNote(checkAutoSave: Boolean = true) {
app.cancelNoteReminders(listOf(NoteIdReminder(id, reminders.value)))
withContext(Dispatchers.IO) { baseNoteDao.delete(id) }
WidgetProvider.sendBroadcast(app, longArrayOf(id))
val attachments = ArrayList(images.value + files.value + audios.value)
if (attachments.isNotEmpty()) {
withContext(Dispatchers.IO) { app.deleteAttachments(attachments) }
}
if (checkAutoSave) {
app.checkBackupOnSave(preferences, forceFullBackup = true)
}
}
fun setItems(items: List<ListItem>) {
this.items.clear()
this.items.addAll(items)
}
suspend fun saveNote(checkBackupOnSave: Boolean = true): Long {
return withContext(Dispatchers.IO) {
val note = getBaseNote()
val id = baseNoteDao.insertSafe(app, note)
if (checkBackupOnSave) {
checkBackupOnSave(note)
}
originalNote = note.deepCopy()
return@withContext id
}
}
suspend fun checkBackupOnSave(note: BaseNote = getBaseNote()) {
app.checkBackupOnSave(
preferences,
note = note,
forceFullBackup = originalNote?.attachmentsDifferFrom(note) == true,
)
}
fun isEmpty(): Boolean {
return title.isEmpty() &&
body.isEmpty() &&
items.none { item -> item.body.isNotEmpty() } &&
files.value.isEmpty() &&
images.value.isEmpty() &&
audios.value.isEmpty()
}
fun isModified(): Boolean {
return getBaseNote() != originalNote
}
private suspend fun updateImages() {
withContext(Dispatchers.IO) { baseNoteDao.updateImages(id, images.value) }
}
private suspend fun updateFiles() {
withContext(Dispatchers.IO) { baseNoteDao.updateFiles(id, files.value) }
}
private suspend fun updateAudios() {
withContext(Dispatchers.IO) { baseNoteDao.updateAudios(id, audios.value) }
}
fun getBaseNote(): BaseNote {
val spans = getFilteredSpans(body)
val body = this.body.toString()
val nonEmptyItems = this.items.filter { item -> item.body.isNotEmpty() }
return BaseNote(
id,
type,
folder,
color,
title,
pinned,
timestamp,
modifiedTimestamp,
labels,
body,
spans,
nonEmptyItems,
images.value,
files.value,
audios.value,
reminders.value,
viewMode.value,
)
}
private fun getFilteredSpans(spanned: Spanned): ArrayList<SpanRepresentation> {
val representations = LinkedHashSet<SpanRepresentation>()
spanned.getSpans<CharacterStyle>().forEach { span ->
val end = spanned.getSpanEnd(span)
val start = spanned.getSpanStart(span)
val representation =
SpanRepresentation(start, end, false, false, null, false, false, false)
when (span) {
is StyleSpan -> {
representation.bold = span.style == Typeface.BOLD
representation.italic = span.style == Typeface.ITALIC
}
is URLSpan -> {
representation.link = true
representation.linkData = span.url
}
is TypefaceSpan -> representation.monospace = span.family == "monospace"
is StrikethroughSpan -> representation.strikethrough = true
}
if (representation.isNotUseless()) {
representations.add(representation)
}
}
return getFilteredRepresentations(ArrayList(representations))
}
private fun getFilteredRepresentations(
representations: ArrayList<SpanRepresentation>
): ArrayList<SpanRepresentation> {
representations.forEachIndexed { index, representation ->
val match =
representations.find { spanRepresentation ->
spanRepresentation.isEqualInSize(representation)
}
if (match != null && representations.indexOf(match) != index) {
if (match.bold) {
representation.bold = true
}
if (match.link) {
representation.link = true
representation.linkData = match.linkData
}
if (match.italic) {
representation.italic = true
}
if (match.monospace) {
representation.monospace = true
}
if (match.strikethrough) {
representation.strikethrough = true
}
val copy = ArrayList(representations)
copy[index] = representation
copy.remove(match)
return getFilteredRepresentations(copy)
}
}
return representations
}
suspend fun removeReminder(reminder: Reminder) {
app.cancelReminder(this.id, reminder.id)
val updatedReminders = reminders.value.filter { it.id != reminder.id }
updateReminders(updatedReminders)
}
suspend fun addReminder(reminder: Reminder) {
val updatedReminders = ArrayList(reminders.value)
val newReminder = reminder.copy(id = (updatedReminders.maxOfOrNull { it.id } ?: -1) + 1)
updatedReminders.add(newReminder)
updateReminders(updatedReminders)
app.scheduleReminder(id, newReminder)
}
suspend fun updateReminder(updatedReminder: Reminder) {
if (updatedReminder.id != NEW_REMINDER_ID) {
app.cancelReminder(id, updatedReminder.id)
}
val updatedReminders = reminders.value.copy().toMutableList()
val idx = updatedReminders.indexOfFirst { it.id == updatedReminder.id }
if (idx != -1) {
updatedReminders[idx] = updatedReminder
updateReminders(updatedReminders)
app.scheduleReminder(id, updatedReminder)
}
}
private suspend fun updateReminders(updatedReminders: List<Reminder>) {
reminders.value = updatedReminders
withContext(Dispatchers.IO) { baseNoteDao.updateReminders(id, updatedReminders) }
}
suspend fun convertTo(noteType: Type) {
when (noteType) {
Type.NOTE -> {
body = SpannableStringBuilder(items.joinToString(separator = "\n") { it.body })
type = Type.NOTE
setItems(ArrayList())
}
Type.LIST -> {
val text = body.toString()
val listSyntaxRegex =
text.findListSyntaxRegex(checkContains = true, plainNewLineAllowed = true)
if (listSyntaxRegex != null) {
setItems(text.extractListItems(listSyntaxRegex))
} else {
setItems(
text.lines().mapIndexed { idx, itemText ->
ListItem(itemText, false, false, idx, mutableListOf())
}
)
}
type = Type.LIST
body = SpannableStringBuilder()
}
}
Cache.list = ArrayList()
saveNote(checkBackupOnSave = false)
}
suspend fun refreshOriginalNote() {
if (id == 0L) return
val baseNote = withContext(Dispatchers.IO) { baseNoteDao.get(id) }
if (baseNote == null) return
originalNote = baseNote.deepCopy()
reminders.value = baseNote.reminders
}
enum class FileType {
IMAGE,
ANY,
}
}