forked from ankidroid/Anki-Android
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCardContentProvider.kt
More file actions
1384 lines (1329 loc) · 62.5 KB
/
CardContentProvider.kt
File metadata and controls
1384 lines (1329 loc) · 62.5 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
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
/***************************************************************************************
* *
* Copyright (c) 2015 Frank Oltmanns <frank.oltmanns@gmail.com> *
* Copyright (c) 2015 Timothy Rae <timothy.rae@gmail.com> *
* Copyright (c) 2016 Mark Carter <mark@marcardar.com> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.anki.provider
import android.annotation.SuppressLint
import android.content.ContentProvider
import android.content.ContentUris
import android.content.ContentValues
import android.content.UriMatcher
import android.content.pm.PackageManager
import android.database.Cursor
import android.database.MatrixCursor
import android.database.sqlite.SQLiteQueryBuilder
import android.net.Uri
import android.webkit.MimeTypeMap
import androidx.core.net.toUri
import com.ichi2.anki.AnkiDroidApp
import com.ichi2.anki.BuildConfig
import com.ichi2.anki.CollectionManager
import com.ichi2.anki.CrashReportService
import com.ichi2.anki.Ease
import com.ichi2.anki.FlashCardsContract
import com.ichi2.anki.common.time.TimeManager
import com.ichi2.anki.common.utils.annotation.KotlinCleanup
import com.ichi2.anki.utils.ext.description
import com.ichi2.libanki.Card
import com.ichi2.libanki.CardId
import com.ichi2.libanki.CardTemplate
import com.ichi2.libanki.Collection
import com.ichi2.libanki.Deck
import com.ichi2.libanki.DeckId
import com.ichi2.libanki.Decks
import com.ichi2.libanki.Note
import com.ichi2.libanki.NoteId
import com.ichi2.libanki.NoteTypeId
import com.ichi2.libanki.NoteTypeKind
import com.ichi2.libanki.NotetypeJson
import com.ichi2.libanki.Notetypes
import com.ichi2.libanki.Sound.replaceWithSoundTags
import com.ichi2.libanki.TemplateManager.TemplateRenderContext.TemplateRenderOutput
import com.ichi2.libanki.Utils
import com.ichi2.libanki.exception.ConfirmModSchemaException
import com.ichi2.libanki.exception.EmptyMediaException
import com.ichi2.libanki.sched.DeckNode
import com.ichi2.utils.FileUtil
import com.ichi2.utils.FileUtil.internalizeUri
import com.ichi2.utils.Permissions.arePermissionsDefinedInManifest
import net.ankiweb.rsdroid.exceptions.BackendDeckIsFilteredException
import org.json.JSONArray
import org.json.JSONException
import timber.log.Timber
import java.io.File
import java.io.IOException
/**
* Supported URIs:
*
* * .../notes (search for notes)
* * .../notes/# (direct access to note)
* * .../notes/#/cards (access cards of note)
* * .../notes/#/cards/# (access specific card of note)
* * .../models (search for models)
* * .../models/# (direct access to model). String id 'current' can be used in place of # for the current note type
* * .../models/#/fields (access to field definitions of a note type)
* * .../models/#/templates (access to card templates of a note type)
* * .../schedule (access the study schedule)
* * .../decks (access the deck list)
* * .../decks/# (access the specified deck)
* * .../selected_deck (access the currently selected deck)
* * .../media (add media files to anki collection.media)
*
* Note that unlike Android's contact providers:
*
* * it's not possible to access cards of more than one note at a time
* * it's not possible to access cards of a note without providing the note's ID
*
*/
class CardContentProvider : ContentProvider() {
companion object {
// URI types
private const val NOTES = 1000
private const val NOTES_ID = 1001
private const val NOTES_ID_CARDS = 1003
private const val NOTES_ID_CARDS_ORD = 1004
private const val NOTES_V2 = 1005
private const val NOTE_TYPES = 2000
private const val NOTE_TYPES_ID = 2001
private const val NOTE_TYPES_ID_EMPTY_CARDS = 2002
private const val NOTE_TYPES_ID_TEMPLATES = 2003
private const val NOTE_TYPES_ID_TEMPLATES_ID = 2004
private const val NOTE_TYPES_ID_FIELDS = 2005
private const val SCHEDULE = 3000
private const val DECKS = 4000
private const val DECK_SELECTED = 4001
private const val DECKS_ID = 4002
private const val MEDIA = 5000
private val sUriMatcher = UriMatcher(UriMatcher.NO_MATCH)
/**
* The names of the columns returned by this content provider differ slightly from the names
* given of the database columns. This list is used to convert the column names used in a
* projection by the user into DB column names.
*
*
* This is currently only "_id" (projection) vs. "id" (Anki DB). But should probably be
* applied to more columns. "MID", "USN", "MOD" are not really user friendly.
*/
private val sDefaultNoteProjectionDBAccess = FlashCardsContract.Note.DEFAULT_PROJECTION.clone()
private fun sanitizeNoteProjection(projection: Array<String>?): Array<String> {
if (projection.isNullOrEmpty()) {
return sDefaultNoteProjectionDBAccess
}
val sanitized = ArrayList<String>(projection.size)
for (column in projection) {
val idx = FlashCardsContract.Note.DEFAULT_PROJECTION.indexOf(column)
if (idx >= 0) {
sanitized.add(sDefaultNoteProjectionDBAccess[idx])
} else {
throw IllegalArgumentException("Unknown column $column")
}
}
return sanitized.toTypedArray()
}
init {
fun addUri(
path: String,
code: Int,
) = sUriMatcher.addURI(FlashCardsContract.AUTHORITY, path, code)
// Here you can see all the URIs at a glance
addUri("notes", NOTES)
addUri("notes_v2", NOTES_V2)
addUri("notes/#", NOTES_ID)
addUri("notes/#/cards", NOTES_ID_CARDS)
addUri("notes/#/cards/#", NOTES_ID_CARDS_ORD)
addUri("models", NOTE_TYPES)
addUri("models/*", NOTE_TYPES_ID) // the note type ID can also be "current"
addUri("models/*/empty_cards", NOTE_TYPES_ID_EMPTY_CARDS)
addUri("models/*/templates", NOTE_TYPES_ID_TEMPLATES)
addUri("models/*/templates/#", NOTE_TYPES_ID_TEMPLATES_ID)
addUri("models/*/fields", NOTE_TYPES_ID_FIELDS)
addUri("schedule/", SCHEDULE)
addUri("decks/", DECKS)
addUri("decks/#", DECKS_ID)
addUri("selected_deck/", DECK_SELECTED)
addUri("media", MEDIA)
for (idx in sDefaultNoteProjectionDBAccess.indices) {
if (sDefaultNoteProjectionDBAccess[idx] == FlashCardsContract.Note._ID) {
sDefaultNoteProjectionDBAccess[idx] = "id as _id"
}
}
}
}
override fun onCreate(): Boolean {
// Initialize content provider on startup.
Timber.d("CardContentProvider: onCreate")
AnkiDroidApp.makeBackendUsable(context!!)
return true
}
// keeps the nullability declared by the platform
@Suppress("RedundantNullableReturnType")
override fun getType(uri: Uri): String? {
// Find out what data the user is requesting
return when (sUriMatcher.match(uri)) {
NOTES_V2, NOTES -> FlashCardsContract.Note.CONTENT_TYPE
NOTES_ID -> FlashCardsContract.Note.CONTENT_ITEM_TYPE
NOTES_ID_CARDS, NOTE_TYPES_ID_EMPTY_CARDS -> FlashCardsContract.Card.CONTENT_TYPE
NOTES_ID_CARDS_ORD -> FlashCardsContract.Card.CONTENT_ITEM_TYPE
NOTE_TYPES -> FlashCardsContract.Model.CONTENT_TYPE
NOTE_TYPES_ID -> FlashCardsContract.Model.CONTENT_ITEM_TYPE
NOTE_TYPES_ID_TEMPLATES -> FlashCardsContract.CardTemplate.CONTENT_TYPE
NOTE_TYPES_ID_TEMPLATES_ID -> FlashCardsContract.CardTemplate.CONTENT_ITEM_TYPE
SCHEDULE -> FlashCardsContract.ReviewInfo.CONTENT_TYPE
DECKS, DECK_SELECTED, DECKS_ID -> FlashCardsContract.Deck.CONTENT_TYPE
else -> throw IllegalArgumentException("uri $uri is not supported")
}
}
/** Only enforce permissions for queries and inserts on Android M and above, or if its a 'rogue client' */
private fun shouldEnforceQueryOrInsertSecurity(): Boolean = knownRogueClient()
/** Enforce permissions for all updates on Android M and above. Otherwise block depending on URI and client app */
private fun shouldEnforceUpdateSecurity(uri: Uri): Boolean {
val whitelist = listOf(NOTES_ID_CARDS_ORD, NOTE_TYPES_ID, NOTE_TYPES_ID_TEMPLATES_ID, SCHEDULE, DECK_SELECTED)
return !whitelist.contains(sUriMatcher.match(uri)) || knownRogueClient()
}
override fun query(
uri: Uri,
projection: Array<String>?,
selection: String?,
selectionArgs: Array<String>?,
order: String?,
): Cursor? {
if (!hasReadWritePermission() && shouldEnforceQueryOrInsertSecurity()) {
throwSecurityException("query", uri)
}
val col = CollectionManager.getColUnsafe()
Timber.d(getLogMessage("query", uri))
// Find out what data the user is requesting
return when (sUriMatcher.match(uri)) {
NOTES_V2 -> {
// Search for notes using direct SQL query
val proj = sanitizeNoteProjection(projection)
val sql = SQLiteQueryBuilder.buildQueryString(false, "notes", proj, selection, null, null, order, null)
col.db.query(sql, *(selectionArgs ?: arrayOf()))
}
NOTES -> {
// Search for notes using the libanki browser syntax
val proj = sanitizeNoteProjection(projection)
val query = selection ?: ""
val noteIds = col.findNotes(query)
if (noteIds.isNotEmpty()) {
val sel = "id in (${noteIds.joinToString(",")})"
val sql = SQLiteQueryBuilder.buildQueryString(false, "notes", proj, sel, null, null, order, null)
col.db.database.query(sql)
} else {
null
}
}
NOTES_ID -> {
// Direct access note with specific ID
val noteId = uri.pathSegments[1]
val proj = sanitizeNoteProjection(projection)
val sql = SQLiteQueryBuilder.buildQueryString(false, "notes", proj, "id=?", null, null, order, null)
col.db.query(sql, noteId)
}
NOTES_ID_CARDS -> {
val currentNote = getNoteFromUri(uri, col)
val columns = projection ?: FlashCardsContract.Card.DEFAULT_PROJECTION
val rv = MatrixCursor(columns, 1)
for (currentCard: Card in currentNote.cards(col)) {
addCardToCursor(currentCard, rv, col, columns)
}
rv
}
NOTES_ID_CARDS_ORD -> {
val currentCard = getCardFromUri(uri, col)
val columns = projection ?: FlashCardsContract.Card.DEFAULT_PROJECTION
val rv = MatrixCursor(columns, 1)
addCardToCursor(currentCard, rv, col, columns)
rv
}
NOTE_TYPES -> {
val columns = projection ?: FlashCardsContract.Model.DEFAULT_PROJECTION
val rv = MatrixCursor(columns, 1)
for (noteTypeId: NoteTypeId in col.notetypes.ids()) {
addNoteTypeToCursor(noteTypeId, col.notetypes, rv, columns)
}
rv
}
NOTE_TYPES_ID -> {
val noteTypeId = getNoteTypeIdFromUri(uri, col)
val columns = projection ?: FlashCardsContract.Model.DEFAULT_PROJECTION
val rv = MatrixCursor(columns, 1)
addNoteTypeToCursor(noteTypeId, col.notetypes, rv, columns)
rv
}
NOTE_TYPES_ID_TEMPLATES -> {
// Direct access note type templates
val currentNoteType = col.notetypes.get(getNoteTypeIdFromUri(uri, col))
val columns = projection ?: FlashCardsContract.CardTemplate.DEFAULT_PROJECTION
val rv = MatrixCursor(columns, 1)
try {
for ((idx, template) in currentNoteType!!.templates.withIndex()) {
addTemplateToCursor(template, currentNoteType, idx + 1, col.notetypes, rv, columns)
}
} catch (e: JSONException) {
throw IllegalArgumentException("Note type is malformed", e)
}
rv
}
NOTE_TYPES_ID_TEMPLATES_ID -> {
// Direct access note type template with specific ID
val ord = uri.lastPathSegment!!.toInt()
val currentNoteType = col.notetypes.get(getNoteTypeIdFromUri(uri, col))
val columns = projection ?: FlashCardsContract.CardTemplate.DEFAULT_PROJECTION
val rv = MatrixCursor(columns, 1)
try {
val template = getTemplateFromUri(uri, col)
addTemplateToCursor(template, currentNoteType, ord + 1, col.notetypes, rv, columns)
} catch (e: JSONException) {
throw IllegalArgumentException("Note type is malformed", e)
}
rv
}
SCHEDULE -> {
val columns = projection ?: FlashCardsContract.ReviewInfo.DEFAULT_PROJECTION
val rv = MatrixCursor(columns, 1)
val selectedDeckBeforeQuery = col.decks.selected()
var deckIdOfTemporarilySelectedDeck: Long = -1
var limit = 1 // the number of scheduled cards to return
var selectionArgIndex = 0
// parsing the selection arguments
if (selection != null) {
val args = selection.split(",").toTypedArray() // split selection to get arguments like "limit=?"
for (arg: String in args) {
val keyAndValue = arg.split("=").toTypedArray() // split arguments into key ("limit") and value ("?")
try {
// check if value is a placeholder ("?"), if so replace with the next value of selectionArgs
val value =
if ("?" == keyAndValue[1].trim()) {
selectionArgs!![selectionArgIndex++]
} else {
keyAndValue[1]
}
if ("limit" == keyAndValue[0].trim()) {
limit = value.toInt()
} else if ("deckID" == keyAndValue[0].trim()) {
deckIdOfTemporarilySelectedDeck = value.toLong()
if (!selectDeckWithCheck(col, deckIdOfTemporarilySelectedDeck)) {
return rv // if the provided deckID is wrong, return empty cursor.
}
}
} catch (nfe: NumberFormatException) {
Timber.w(nfe)
}
}
}
// retrieve the number of cards provided by the selection parameter "limit"
val cards =
col.backend
.getQueuedCards(
fetchLimit = limit,
intradayLearningOnly = false,
).cardsList
.map { Card(it.card) }
val buttonCount = 4
var k = 0
while (k < limit) {
val currentCard = cards.getOrNull(k) ?: break
val buttonTexts = JSONArray()
var i = 0
while (i < buttonCount) {
buttonTexts.put(col.sched.nextIvlStr(currentCard, Ease.fromValue(i + 1)))
i++
}
addReviewInfoToCursor(currentCard, buttonTexts, buttonCount, rv, col, columns)
k++
}
if (deckIdOfTemporarilySelectedDeck != -1L) { // if the selected deck was changed
// change the selected deck back to the one it was before the query
col.decks.select(selectedDeckBeforeQuery)
}
rv
}
DECKS -> {
val columns = projection ?: FlashCardsContract.Deck.DEFAULT_PROJECTION
val allDecks = col.sched.deckDueTree()
val rv = MatrixCursor(columns, 1)
allDecks.forEach {
addDeckToCursor(
it.did,
it.fullDeckName,
getDeckCountsFromDueTreeNode(it),
rv,
col,
columns,
)
}
rv
}
DECKS_ID -> {
// Direct access deck
val columns = projection ?: FlashCardsContract.Deck.DEFAULT_PROJECTION
val rv = MatrixCursor(columns, 1)
val allDecks = col.sched.deckDueTree()
val desiredDeckId = uri.pathSegments[1].toLong()
allDecks.find(desiredDeckId)?.let {
addDeckToCursor(it.did, it.fullDeckName, getDeckCountsFromDueTreeNode(it), rv, col, columns)
}
rv
}
DECK_SELECTED -> {
val id = col.decks.selected()
val name = col.decks.name(id)
val columns = projection ?: FlashCardsContract.Deck.DEFAULT_PROJECTION
val rv = MatrixCursor(columns, 1)
val counts = JSONArray(listOf(col.sched.counts()))
addDeckToCursor(id, name, counts, rv, col, columns)
rv
}
else -> throw IllegalArgumentException("uri $uri is not supported")
}
}
private fun getDeckCountsFromDueTreeNode(deck: DeckNode): JSONArray =
JSONArray().apply {
put(deck.lrnCount)
put(deck.revCount)
put(deck.newCount)
}
@SuppressLint("CheckResult")
override fun update(
uri: Uri,
values: ContentValues?,
selection: String?,
selectionArgs: Array<String>?,
): Int {
if (!hasReadWritePermission() && shouldEnforceUpdateSecurity(uri)) {
throwSecurityException("update", uri)
}
val col = CollectionManager.getColUnsafe()
Timber.d(getLogMessage("update", uri))
// Find out what data the user is requesting
val match = sUriMatcher.match(uri)
var updated = 0 // Number of updated entries (return value)
when (match) {
NOTES_V2, NOTES -> throw IllegalArgumentException("Not possible to update notes directly (only through data URI)")
NOTES_ID -> {
/* Direct access note details
*/
val currentNote = getNoteFromUri(uri, col)
// the key of the ContentValues contains the column name
// the value of the ContentValues contains the row value.
val valueSet = values!!.valueSet()
for ((key, tags) in valueSet) {
// when the client does not specify FLDS, then don't update the FLDS
when (key) {
FlashCardsContract.Note.FLDS -> {
// Update FLDS
Timber.d("CardContentProvider: flds update...")
val newFldsEncoded = tags as String
val flds = Utils.splitFields(newFldsEncoded)
// Check that correct number of flds specified
require(flds.size == currentNote.fields.size) { "Incorrect flds argument : $newFldsEncoded" }
// Update the note
var idx = 0
while (idx < flds.size) {
currentNote.setField(idx, flds[idx])
idx++
}
updated++
}
FlashCardsContract.Note.TAGS -> {
// Update tags
Timber.d("CardContentProvider: tags update...")
if (tags != null) {
currentNote.setTagsFromStr(col, tags.toString())
}
updated++
}
else -> {
// Unsupported column
throw IllegalArgumentException("Unsupported column: $key")
}
}
}
Timber.d("CardContentProvider: Saving note...")
col.updateNote(currentNote)
}
NOTES_ID_CARDS -> throw UnsupportedOperationException("Not yet implemented")
NOTES_ID_CARDS_ORD -> {
val currentCard = getCardFromUri(uri, col)
var isDeckUpdate = false
var did = Decks.NOT_FOUND_DECK_ID
// the key of the ContentValues contains the column name
// the value of the ContentValues contains the row value.
val valueSet = values!!.valueSet()
for ((key) in valueSet) {
// Only updates on deck id is supported
isDeckUpdate = key == FlashCardsContract.Card.DECK_ID
did = values.getAsLong(key)
}
require(!col.decks.isFiltered(did)) { "Cards cannot be moved to a filtered deck" }
/* now update the card
*/
if (isDeckUpdate && did >= 0) {
Timber.d("CardContentProvider: Moving card to other deck...")
currentCard.did = did
col.updateCard(currentCard)
updated++
} else {
// User tries an operation that is not (yet?) supported.
throw IllegalArgumentException("Currently only updates of decks are supported")
}
}
NOTE_TYPES -> throw IllegalArgumentException("Cannot update models in bulk")
NOTE_TYPES_ID -> {
// Get the input parameters
val newNoteTypeName = values!!.getAsString(FlashCardsContract.Model.NAME)
val newCss = values.getAsString(FlashCardsContract.Model.CSS)
val newDid = values.getAsString(FlashCardsContract.Model.DECK_ID)
val newFieldList = values.getAsString(FlashCardsContract.Model.FIELD_NAMES)
require(newFieldList == null) {
// Changing the field names would require a full-sync
"Field names cannot be changed via provider"
}
val newSortf = values.getAsInteger(FlashCardsContract.Model.SORT_FIELD_INDEX)
val newType = values.getAsInteger(FlashCardsContract.Model.TYPE)?.let(NoteTypeKind::fromCode)
val newLatexPost = values.getAsString(FlashCardsContract.Model.LATEX_POST)
val newLatexPre = values.getAsString(FlashCardsContract.Model.LATEX_PRE)
// Get the original note JSON
val noteType = col.notetypes.get(getNoteTypeIdFromUri(uri, col))
try {
// Update noteType name and/or css
if (newNoteTypeName != null) {
noteType!!.name = newNoteTypeName
updated++
}
if (newCss != null) {
noteType!!.css = newCss
updated++
}
if (newDid != null) {
if (col.decks.isFiltered(newDid.toLong())) {
throw IllegalArgumentException("Cannot set a filtered deck as default deck for a noteType")
}
noteType!!.did = newDid.toLong()
updated++
}
if (newSortf != null) {
noteType!!.sortf = newSortf
updated++
}
if (newType != null) {
noteType!!.type = newType
updated++
}
if (newLatexPost != null) {
noteType!!.latexPost = newLatexPost
updated++
}
if (newLatexPre != null) {
noteType!!.latexPre = newLatexPre
updated++
}
col.notetypes.save(noteType!!)
} catch (e: JSONException) {
Timber.e(e, "JSONException updating noteType")
}
}
NOTE_TYPES_ID_TEMPLATES -> throw IllegalArgumentException("Cannot update templates in bulk")
NOTE_TYPES_ID_TEMPLATES_ID -> {
val noteTypeId = values!!.getAsLong(FlashCardsContract.CardTemplate.MODEL_ID)
val ord = values.getAsInteger(FlashCardsContract.CardTemplate.ORD)
val name = values.getAsString(FlashCardsContract.CardTemplate.NAME)
val qfmt = values.getAsString(FlashCardsContract.CardTemplate.QUESTION_FORMAT)
val afmt = values.getAsString(FlashCardsContract.CardTemplate.ANSWER_FORMAT)
val bqfmt = values.getAsString(FlashCardsContract.CardTemplate.BROWSER_QUESTION_FORMAT)
val bafmt = values.getAsString(FlashCardsContract.CardTemplate.BROWSER_ANSWER_FORMAT)
// Throw exception if read-only fields are included
if (noteTypeId != null || ord != null) {
throw IllegalArgumentException("Updates to mid or ord are not allowed")
}
// Update the noteType
try {
val templateOrd = uri.lastPathSegment!!.toInt()
val existingNoteType = col.notetypes.get(getNoteTypeIdFromUri(uri, col))
val templates = existingNoteType!!.templates
val template = templates[templateOrd]
if (name != null) {
template.name = name
updated++
}
if (qfmt != null) {
template.qfmt = qfmt
updated++
}
if (afmt != null) {
template.afmt = afmt
updated++
}
if (bqfmt != null) {
template.bqfmt = bqfmt
updated++
}
if (bafmt != null) {
template.bafmt = bafmt
updated++
}
// Save the note type
templates[templateOrd] = template
existingNoteType.templates = templates
col.notetypes.save(existingNoteType)
} catch (e: JSONException) {
throw IllegalArgumentException("Note type is malformed", e)
}
}
SCHEDULE -> {
val valueSet = values!!.valueSet()
var cardOrd = -1
var noteId: NoteId = -1
var ease: Ease? = null
var timeTaken: Long = -1
var bury = -1
var suspend = -1
for ((key) in valueSet) {
when (key) {
FlashCardsContract.ReviewInfo.NOTE_ID -> noteId = values.getAsLong(key)
FlashCardsContract.ReviewInfo.CARD_ORD -> cardOrd = values.getAsInteger(key)
FlashCardsContract.ReviewInfo.EASE ->
ease = Ease.fromValue(values.getAsInteger(key))
FlashCardsContract.ReviewInfo.TIME_TAKEN ->
timeTaken =
values.getAsLong(key)
FlashCardsContract.ReviewInfo.BURY -> bury = values.getAsInteger(key)
FlashCardsContract.ReviewInfo.SUSPEND -> suspend = values.getAsInteger(key)
}
}
if (cardOrd != -1 && noteId != -1L) {
val cardToAnswer: Card = getCard(noteId, cardOrd, col)
@Suppress("SENSELESS_COMPARISON")
@KotlinCleanup("based on getCard() method, cardToAnswer does seem to be not null")
if (cardToAnswer != null) {
if (bury == 1) {
// bury card
buryOrSuspendCard(col, cardToAnswer, true)
} else if (suspend == 1) {
// suspend card
buryOrSuspendCard(col, cardToAnswer, false)
} else {
answerCard(col, cardToAnswer, ease!!, timeTaken)
}
updated++
} else {
Timber.e(
"Requested card with noteId %d and cardOrd %d was not found. Either the provided " +
"noteId/cardOrd were wrong or the card has been deleted in the meantime.",
noteId,
cardOrd,
)
}
}
}
DECKS -> throw IllegalArgumentException("Can't update decks in bulk")
DECKS_ID -> throw UnsupportedOperationException("Not yet implemented")
DECK_SELECTED -> {
val valueSet = values!!.valueSet()
for ((key) in valueSet) {
if (key == FlashCardsContract.Deck.DECK_ID) {
val deckId = values.getAsLong(key)
if (selectDeckWithCheck(col, deckId)) {
updated++
}
}
}
}
else -> throw IllegalArgumentException("uri $uri is not supported")
}
return updated
}
override fun delete(
uri: Uri,
selection: String?,
selectionArgs: Array<String>?,
): Int {
if (!hasReadWritePermission()) {
throwSecurityException("delete", uri)
}
val col = CollectionManager.getColUnsafe()
Timber.d(getLogMessage("delete", uri))
return when (sUriMatcher.match(uri)) {
NOTES_ID -> {
col.removeNotes(nids = listOf(uri.pathSegments[1].toLong()))
1
}
NOTE_TYPES_ID_EMPTY_CARDS -> {
val noteType = col.notetypes.get(getNoteTypeIdFromUri(uri, col)) ?: return -1
val cardIdsToRemove = noteType.getEmptyCardIds(col)
return col.removeCardsAndOrphanedNotes(cardIdsToRemove).count
}
else -> throw UnsupportedOperationException()
}
}
/**
* This can be used to insert multiple notes into a single deck. The deck is specified as a query parameter.
*
* For example: content://com.ichi2.anki.flashcards/notes?deckId=1234567890123
*
* @param uri content Uri
* @param values for notes uri, it is acceptable for values to contain null items. Such items will be skipped
* @return number of notes added (does not include existing notes that were updated)
*/
override fun bulkInsert(
uri: Uri,
values: Array<ContentValues>,
): Int {
if (!hasReadWritePermission() && shouldEnforceQueryOrInsertSecurity()) {
throwSecurityException("bulkInsert", uri)
}
// by default, #bulkInsert simply calls insert for each item in #values
// but in some cases, we want to override this behavior
val match = sUriMatcher.match(uri)
if (match == NOTES) {
val deckIdStr = uri.getQueryParameter(FlashCardsContract.Note.DECK_ID_QUERY_PARAM)
if (deckIdStr != null) {
try {
val deckId = deckIdStr.toLong()
return bulkInsertNotes(values, deckId)
} catch (e: NumberFormatException) {
Timber.d(e, "Invalid %s: %s", FlashCardsContract.Note.DECK_ID_QUERY_PARAM, deckIdStr)
}
}
// deckId not specified, so default to #super implementation (as in spec version 1)
}
return super.bulkInsert(uri, values)
}
/**
* This implementation optimizes for when the notes are grouped according to note type.
*/
private fun bulkInsertNotes(
valuesArr: Array<ContentValues>?,
deckId: DeckId,
): Int {
if (valuesArr.isNullOrEmpty()) {
return 0
}
val col = CollectionManager.getColUnsafe()
if (col.decks.isFiltered(deckId)) {
throw IllegalArgumentException("A filtered deck cannot be specified as the deck in bulkInsertNotes")
}
Timber.d("bulkInsertNotes: %d items.\n%s", valuesArr.size, getLogMessage("bulkInsert", null))
var result = 0
for (i in valuesArr.indices) {
val values: ContentValues = valuesArr[i]
val flds = values.getAsString(FlashCardsContract.Note.FLDS) ?: continue
// val allowEmpty = AllowEmpty.fromBoolean(values.getAsBoolean(FlashCardsContract.Note.ALLOW_EMPTY))
val thisNoteTypeId = values.getAsLong(FlashCardsContract.Note.MID)
if (thisNoteTypeId == null || thisNoteTypeId < 0) {
Timber.d("Unable to get note type at index: %d", i)
continue
}
val fldsArray = Utils.splitFields(flds)
// Create empty note
val newNote = Note.fromNotetypeId(col, thisNoteTypeId)
// Set fields
// Check that correct number of flds specified
if (fldsArray.size != newNote.fields.size) {
throw IllegalArgumentException("Incorrect flds argument : $flds")
}
for (idx in fldsArray.indices) {
newNote.setField(idx, fldsArray[idx])
}
// Set tags
val tags = values.getAsString(FlashCardsContract.Note.TAGS)
if (tags != null) {
newNote.setTagsFromStr(col, tags)
}
// Add to collection
col.addNote(newNote, deckId)
for (card: Card in newNote.cards(col)) {
card.did = deckId
col.updateCard(card)
}
result++
}
return result
}
override fun insert(
uri: Uri,
values: ContentValues?,
): Uri? {
if (!hasReadWritePermission() && shouldEnforceQueryOrInsertSecurity()) {
throwSecurityException("insert", uri)
}
val col = CollectionManager.getColUnsafe()
Timber.d(getLogMessage("insert", uri))
// Find out what data the user is requesting
return when (sUriMatcher.match(uri)) {
NOTES -> {
/* Insert new note with specified fields and tags
*/
val noteTypeId = values!!.getAsLong(FlashCardsContract.Note.MID)
val flds = values.getAsString(FlashCardsContract.Note.FLDS)
val tags = values.getAsString(FlashCardsContract.Note.TAGS)
// val allowEmpty = AllowEmpty.fromBoolean(values.getAsBoolean(FlashCardsContract.Note.ALLOW_EMPTY))
// Create empty note
val newNote = Note.fromNotetypeId(col, noteTypeId)
// Set fields
val fldsArray = Utils.splitFields(flds)
// Check that correct number of flds specified
if (fldsArray.size != newNote.fields.size) {
throw IllegalArgumentException("Incorrect flds argument : $flds")
}
var idx = 0
while (idx < fldsArray.size) {
newNote.setField(idx, fldsArray[idx])
idx++
}
// Set tags
if (tags != null) {
newNote.setTagsFromStr(col, tags)
}
// Add to collection
col.addNote(newNote, newNote.notetype.did)
Uri.withAppendedPath(FlashCardsContract.Note.CONTENT_URI, newNote.id.toString())
}
NOTES_ID -> throw IllegalArgumentException("Not possible to insert note with specific ID")
NOTES_ID_CARDS, NOTES_ID_CARDS_ORD -> throw IllegalArgumentException(
"Not possible to insert cards directly (only through NOTES)",
)
NOTE_TYPES -> {
// Get input arguments
val noteTypeName = values!!.getAsString(FlashCardsContract.Model.NAME)
val css = values.getAsString(FlashCardsContract.Model.CSS)
val did = values.getAsLong(FlashCardsContract.Model.DECK_ID)
val fieldNames = values.getAsString(FlashCardsContract.Model.FIELD_NAMES)
val numCards = values.getAsInteger(FlashCardsContract.Model.NUM_CARDS)
val sortf = values.getAsInteger(FlashCardsContract.Model.SORT_FIELD_INDEX)
val type = values.getAsInteger(FlashCardsContract.Model.TYPE)?.let(NoteTypeKind::fromCode)
val latexPost = values.getAsString(FlashCardsContract.Model.LATEX_POST)
val latexPre = values.getAsString(FlashCardsContract.Model.LATEX_PRE)
// Throw exception if required fields empty
if (noteTypeName == null || fieldNames == null || numCards == null) {
throw IllegalArgumentException("Note type name, field_names, and num_cards can't be empty")
}
if (did != null && col.decks.isFiltered(did)) {
throw IllegalArgumentException("Cannot set a filtered deck as default deck for a note type")
}
// Create a new note type
val newNoteType = col.notetypes.new(noteTypeName)
return try {
// Add the fields
val allFields = Utils.splitFields(fieldNames)
for (f: String? in allFields) {
col.notetypes.addFieldInNewNoteType(newNoteType, col.notetypes.newField(f!!))
}
// Add some empty card templates
var idx = 0
while (idx < numCards) {
val cardName = CollectionManager.TR.cardTemplatesCard(idx + 1)
val t = Notetypes.newTemplate(cardName)
t.qfmt = "{{${allFields[0]}}}"
var answerField: String? = allFields[0]
if (allFields.size > 1) {
answerField = allFields[1]
}
t.afmt = "{{FrontSide}}\\n\\n<hr id=answer>\\n\\n{{$answerField}}"
col.notetypes.addTemplateInNewNoteType(newNoteType, t)
idx++
}
// Add the CSS if specified
if (css != null) {
newNoteType.css = css
}
// Add the did if specified
if (did != null) {
newNoteType.did = did
}
if (sortf != null && sortf < allFields.size) {
newNoteType.sortf = sortf
}
if (type != null) {
newNoteType.type = type
}
if (latexPost != null) {
newNoteType.latexPost = latexPost
}
if (latexPre != null) {
newNoteType.latexPre = latexPre
}
// Add the note type to collection (from this point on edits will require a full-sync)
col.notetypes.add(newNoteType)
// Get the mid and return a URI
val noteTypeId = newNoteType.id.toString()
Uri.withAppendedPath(FlashCardsContract.Model.CONTENT_URI, noteTypeId)
} catch (e: JSONException) {
Timber.e(e, "Could not set a field of new note type %s", noteTypeName)
null
}
}
NOTE_TYPES_ID -> throw IllegalArgumentException("Not possible to insert note type with specific ID")
NOTE_TYPES_ID_TEMPLATES -> {
run {
val noteTypeId: NoteTypeId = getNoteTypeIdFromUri(uri, col)
val existingNoteType: NotetypeJson =
col.notetypes.get(noteTypeId)
?: throw IllegalArgumentException("note type missing: $noteTypeId")
val name: String = values!!.getAsString(FlashCardsContract.CardTemplate.NAME)
val qfmt: String = values.getAsString(FlashCardsContract.CardTemplate.QUESTION_FORMAT)
val afmt: String = values.getAsString(FlashCardsContract.CardTemplate.ANSWER_FORMAT)
val bqfmt: String = values.getAsString(FlashCardsContract.CardTemplate.BROWSER_QUESTION_FORMAT)
val bafmt: String = values.getAsString(FlashCardsContract.CardTemplate.BROWSER_ANSWER_FORMAT)
try {
var t: CardTemplate =
Notetypes.newTemplate(name).also { tmpl ->
tmpl.qfmt = qfmt
tmpl.afmt = afmt
tmpl.bqfmt = bqfmt
tmpl.bafmt = bafmt
}
col.notetypes.addTemplate(existingNoteType, t)
col.notetypes.update(existingNoteType)
t = existingNoteType.templates.last()
return ContentUris.withAppendedId(uri, t.ord.toLong())
} catch (e: ConfirmModSchemaException) {
throw IllegalArgumentException("Unable to add template without user requesting/accepting full-sync", e)
} catch (e: JSONException) {
throw IllegalArgumentException("Unable to get ord from new template", e)
}
}
}
NOTE_TYPES_ID_TEMPLATES_ID -> throw IllegalArgumentException("Not possible to insert template with specific ORD")
NOTE_TYPES_ID_FIELDS -> {
run {
val noteTypeId: NoteTypeId = getNoteTypeIdFromUri(uri, col)
val existingNoteType: NotetypeJson =
col.notetypes.get(noteTypeId)
?: throw IllegalArgumentException("note type missing: $noteTypeId")
val name: String =
values!!.getAsString(FlashCardsContract.Model.FIELD_NAME)
?: throw IllegalArgumentException("field name missing for note type: $noteTypeId")
val field = col.notetypes.newField(name)
try {
col.notetypes.addFieldLegacy(existingNoteType, field)
val flds = existingNoteType.fields
return ContentUris.withAppendedId(uri, (flds.length() - 1).toLong())
} catch (e: ConfirmModSchemaException) {
throw IllegalArgumentException("Unable to insert field: $name", e)
} catch (e: JSONException) {
throw IllegalArgumentException("Unable to get newly created field: $name", e)
}
}
}
SCHEDULE -> throw IllegalArgumentException("Not possible to perform insert operation on schedule")
DECKS -> {
// Insert new deck with specified name
val deckName = values!!.getAsString(FlashCardsContract.Deck.DECK_NAME)
var did = col.decks.idForName(deckName)
if (did != null) {
throw IllegalArgumentException("Deck name already exists: $deckName")
}
if (!Decks.isValidDeckName(deckName)) {
throw IllegalArgumentException("Invalid deck name '$deckName'")
}
try {
did = col.decks.id(deckName)
} catch (filteredSubdeck: BackendDeckIsFilteredException) {
throw IllegalArgumentException(filteredSubdeck.message)
}
val deck: Deck = col.decks.get(did)!!
@KotlinCleanup("remove the null check if deck is found to be not null in DeckManager.get(Long)")
@Suppress("SENSELESS_COMPARISON")
if (deck != null) {
try {
val deckDesc = values.getAsString(FlashCardsContract.Deck.DECK_DESC)
if (deckDesc != null) {
deck.put("desc", deckDesc)
}
} catch (e: JSONException) {
Timber.e(e, "Could not set a field of new deck %s", deckName)
return null
}
}
Uri.withAppendedPath(FlashCardsContract.Deck.CONTENT_ALL_URI, did.toString())
}
DECK_SELECTED -> throw IllegalArgumentException("Selected deck can only be queried and updated")
DECKS_ID -> throw IllegalArgumentException("Not possible to insert deck with specific ID")
MEDIA ->
// insert a media file
// contentvalue should have data and preferredFileName values
insertMediaFile(values, col)
else -> throw IllegalArgumentException("uri $uri is not supported")
}
}
private fun insertMediaFile(
values: ContentValues?,
col: Collection,