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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
|
# Copyright 2016-2021 Alex Yatskov
#
# 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/>.
import aqt
anki_version = tuple(int(segment) for segment in aqt.appVersion.split("."))
if anki_version < (2, 1, 45):
raise Exception("Minimum Anki version supported: 2.1.45")
import base64
import glob
import hashlib
import inspect
import json
import os
import os.path
import platform
import re
import time
import unicodedata
import anki
import anki.exporting
import anki.storage
from anki.cards import Card
from anki.consts import MODEL_CLOZE
from anki.exporting import AnkiPackageExporter
from anki.importing import AnkiPackageImporter
from anki.notes import Note
from anki.errors import NotFoundError
from aqt.qt import Qt, QTimer, QMessageBox, QCheckBox
from .web import format_exception_reply, format_success_reply
from .edit import Edit
from . import web, util
#
# AnkiConnect
#
class AnkiConnect:
def __init__(self):
self.log = None
self.timer = None
self.server = web.WebServer(self.handler)
def initLogging(self):
logPath = util.setting('apiLogPath')
if logPath is not None:
self.log = open(logPath, 'w')
def startWebServer(self):
try:
self.server.listen()
# only keep reference to prevent garbage collection
self.timer = QTimer()
self.timer.timeout.connect(self.advance)
self.timer.start(util.setting('apiPollInterval'))
except:
QMessageBox.critical(
self.window(),
'AnkiConnect',
'Failed to listen on port {}.\nMake sure it is available and is not in use.'.format(util.setting('webBindPort'))
)
def save_model(self, models, ankiModel):
models.update_dict(ankiModel)
def logEvent(self, name, data):
if self.log is not None:
self.log.write('[{}]\n'.format(name))
json.dump(data, self.log, indent=4, sort_keys=True)
self.log.write('\n\n')
self.log.flush()
def advance(self):
self.server.advance()
def handler(self, request):
self.logEvent('request', request)
name = request.get('action', '')
version = request.get('version', 4)
params = request.get('params', {})
key = request.get('key')
try:
if key != util.setting('apiKey') and name != 'requestPermission':
raise Exception('valid api key must be provided')
method = None
for methodName, methodInst in inspect.getmembers(self, predicate=inspect.ismethod):
apiVersionLast = 0
apiNameLast = None
if getattr(methodInst, 'api', False):
for apiVersion, apiName in getattr(methodInst, 'versions', []):
if apiVersionLast < apiVersion <= version:
apiVersionLast = apiVersion
apiNameLast = apiName
if apiNameLast is None and apiVersionLast == 0:
apiNameLast = methodName
if apiNameLast is not None and apiNameLast == name:
method = methodInst
break
if method is None:
raise Exception('unsupported action')
api_return_value = methodInst(**params)
reply = format_success_reply(version, api_return_value)
except Exception as e:
reply = format_exception_reply(version, e)
self.logEvent('reply', reply)
return reply
def window(self):
return aqt.mw
def reviewer(self):
reviewer = self.window().reviewer
if reviewer is None:
raise Exception('reviewer is not available')
return reviewer
def collection(self):
collection = self.window().col
if collection is None:
raise Exception('collection is not available')
return collection
def decks(self):
decks = self.collection().decks
if decks is None:
raise Exception('decks are not available')
return decks
def scheduler(self):
scheduler = self.collection().sched
if scheduler is None:
raise Exception('scheduler is not available')
return scheduler
def database(self):
database = self.collection().db
if database is None:
raise Exception('database is not available')
return database
def media(self):
media = self.collection().media
if media is None:
raise Exception('media is not available')
return media
def startEditing(self):
self.window().requireReset()
def stopEditing(self):
if self.collection() is not None:
self.window().maybeReset()
def createNote(self, note):
collection = self.collection()
model = collection.models.byName(note['modelName'])
if model is None:
raise Exception('model was not found: {}'.format(note['modelName']))
deck = collection.decks.byName(note['deckName'])
if deck is None:
raise Exception('deck was not found: {}'.format(note['deckName']))
ankiNote = anki.notes.Note(collection, model)
ankiNote.model()['did'] = deck['id']
if 'tags' in note:
ankiNote.tags = note['tags']
for name, value in note['fields'].items():
for ankiName in ankiNote.keys():
if name.lower() == ankiName.lower():
ankiNote[ankiName] = value
break
allowDuplicate = False
duplicateScope = None
duplicateScopeDeckName = None
duplicateScopeCheckChildren = False
duplicateScopeCheckAllModels = False
if 'options' in note:
options = note['options']
if 'allowDuplicate' in options:
allowDuplicate = options['allowDuplicate']
if type(allowDuplicate) is not bool:
raise Exception('option parameter "allowDuplicate" must be boolean')
if 'duplicateScope' in options:
duplicateScope = options['duplicateScope']
if 'duplicateScopeOptions' in options:
duplicateScopeOptions = options['duplicateScopeOptions']
if 'deckName' in duplicateScopeOptions:
duplicateScopeDeckName = duplicateScopeOptions['deckName']
if 'checkChildren' in duplicateScopeOptions:
duplicateScopeCheckChildren = duplicateScopeOptions['checkChildren']
if type(duplicateScopeCheckChildren) is not bool:
raise Exception('option parameter "duplicateScopeOptions.checkChildren" must be boolean')
if 'checkAllModels' in duplicateScopeOptions:
duplicateScopeCheckAllModels = duplicateScopeOptions['checkAllModels']
if type(duplicateScopeCheckAllModels) is not bool:
raise Exception('option parameter "duplicateScopeOptions.checkAllModels" must be boolean')
duplicateOrEmpty = self.isNoteDuplicateOrEmptyInScope(
ankiNote,
deck,
collection,
duplicateScope,
duplicateScopeDeckName,
duplicateScopeCheckChildren,
duplicateScopeCheckAllModels
)
if duplicateOrEmpty == 1:
raise Exception('cannot create note because it is empty')
elif duplicateOrEmpty == 2:
if allowDuplicate:
return ankiNote
raise Exception('cannot create note because it is a duplicate')
elif duplicateOrEmpty == 0:
return ankiNote
else:
raise Exception('cannot create note for unknown reason')
def isNoteDuplicateOrEmptyInScope(
self,
note,
deck,
collection,
duplicateScope,
duplicateScopeDeckName,
duplicateScopeCheckChildren,
duplicateScopeCheckAllModels
):
# Returns: 1 if first is empty, 2 if first is a duplicate, 0 otherwise.
# note.dupeOrEmpty returns if a note is a global duplicate with the specific model.
# This is used as the default check, and the rest of this function is manually
# checking if the note is a duplicate with additional options.
if duplicateScope != 'deck' and not duplicateScopeCheckAllModels:
return note.dupeOrEmpty() or 0
# Primary field for uniqueness
val = note.fields[0]
if not val.strip():
return 1
csum = anki.utils.fieldChecksum(val)
# Create dictionary of deck ids
dids = None
if duplicateScope == 'deck':
did = deck['id']
if duplicateScopeDeckName is not None:
deck2 = collection.decks.byName(duplicateScopeDeckName)
if deck2 is None:
# Invalid deck, so cannot be duplicate
return 0
did = deck2['id']
dids = {did: True}
if duplicateScopeCheckChildren:
for kv in collection.decks.children(did):
dids[kv[1]] = True
# Build query
query = 'select id from notes where csum=?'
queryArgs = [csum]
if note.id:
query += ' and id!=?'
queryArgs.append(note.id)
if not duplicateScopeCheckAllModels:
query += ' and mid=?'
queryArgs.append(note.mid)
# Search
for noteId in note.col.db.list(query, *queryArgs):
if dids is None:
# Duplicate note exists in the collection
return 2
# Validate that a card exists in one of the specified decks
for cardDeckId in note.col.db.list('select did from cards where nid=?', noteId):
if cardDeckId in dids:
return 2
# Not a duplicate
return 0
def getCard(self, card_id: int) -> Card:
try:
return self.collection().getCard(card_id)
except NotFoundError:
raise NotFoundError('Card was not found: {}'.format(card_id))
def getNote(self, note_id: int) -> Note:
try:
return self.collection().getNote(note_id)
except NotFoundError:
raise NotFoundError('Note was not found: {}'.format(note_id))
def deckStatsToJson(self, due_tree):
deckStats = {'deck_id': due_tree.deck_id,
'name': due_tree.name,
'new_count': due_tree.new_count,
'learn_count': due_tree.learn_count,
'review_count': due_tree.review_count}
if anki_version > (2, 1, 46):
# total_in_deck is not supported on lower Anki versions
deckStats['total_in_deck'] = due_tree.total_in_deck
return deckStats
def collectDeckTreeChildren(self, parent_node):
allNodes = {parent_node.deck_id: parent_node}
for child in parent_node.children:
for deckId, childNode in self.collectDeckTreeChildren(child).items():
allNodes[deckId] = childNode
return allNodes
#
# Miscellaneous
#
@util.api()
def version(self):
return util.setting('apiVersion')
@util.api()
def requestPermission(self, origin, allowed):
results = {
"permission": "denied",
}
if allowed:
results = {
"permission": "granted",
"requireApikey": bool(util.setting('apiKey')),
"version": util.setting('apiVersion')
}
elif origin in util.setting('ignoreOriginList'):
pass # defaults to denied
else: # prompt the user
msg = QMessageBox(None)
msg.setWindowTitle("A website wants to access to Anki")
msg.setText('"{}" requests permission to use Anki through AnkiConnect. Do you want to give it access?'.format(origin))
msg.setInformativeText("By granting permission, you'll allow the website to modify your collection on your behalf, including the execution of destructive actions such as deck deletion.")
msg.setWindowIcon(self.window().windowIcon())
msg.setIcon(QMessageBox.Question)
msg.setStandardButtons(QMessageBox.Yes|QMessageBox.No)
msg.setDefaultButton(QMessageBox.No)
msg.setCheckBox(QCheckBox(text='Ignore further requests from "{}"'.format(origin), parent=msg))
msg.setWindowFlags(Qt.WindowStaysOnTopHint)
pressedButton = msg.exec_()
if pressedButton == QMessageBox.Yes:
config = aqt.mw.addonManager.getConfig(__name__)
config["webCorsOriginList"] = util.setting('webCorsOriginList')
config["webCorsOriginList"].append(origin)
aqt.mw.addonManager.writeConfig(__name__, config)
results = {
"permission": "granted",
"requireApikey": bool(util.setting('apiKey')),
"version": util.setting('apiVersion')
}
# if the origin isn't an empty string, the user clicks "No", and the ignore box is checked
elif origin and pressedButton == QMessageBox.No and msg.checkBox().isChecked():
config = aqt.mw.addonManager.getConfig(__name__)
config["ignoreOriginList"] = util.setting('ignoreOriginList')
config["ignoreOriginList"].append(origin)
aqt.mw.addonManager.writeConfig(__name__, config)
# else defaults to denied
return results
@util.api()
def getProfiles(self):
return self.window().pm.profiles()
@util.api()
def loadProfile(self, name):
if name not in self.window().pm.profiles():
return False
if self.window().isVisible():
cur_profile = self.window().pm.name
if cur_profile != name:
self.window().unloadProfileAndShowProfileManager()
def waiter():
# This function waits until main window is closed
# It's needed cause sync can take quite some time
# And if we call loadProfile until sync is ended things will go wrong
if self.window().isVisible():
QTimer.singleShot(1000, waiter)
else:
self.loadProfile(name)
waiter()
else:
self.window().pm.load(name)
self.window().loadProfile()
self.window().profileDiag.closeWithoutQuitting()
return True
@util.api()
def sync(self):
self.window().onSync()
@util.api()
def multi(self, actions):
return list(map(self.handler, actions))
@util.api()
def getNumCardsReviewedToday(self):
return self.database().scalar('select count() from revlog where id > ?', (self.scheduler().dayCutoff - 86400) * 1000)
@util.api()
def getNumCardsReviewedByDay(self):
return self.database().all('select date(id/1000 - ?, "unixepoch", "localtime") as day, count() from revlog group by day order by day desc',
int(time.strftime("%H", time.localtime(self.scheduler().dayCutoff))) * 3600)
@util.api()
def getCollectionStatsHTML(self, wholeCollection=True):
stats = self.collection().stats()
stats.wholeCollection = wholeCollection
return stats.report()
#
# Decks
#
@util.api()
def deckNames(self):
return self.decks().allNames()
@util.api()
def deckNamesAndIds(self):
decks = {}
for deck in self.deckNames():
decks[deck] = self.decks().id(deck)
return decks
@util.api()
def getDecks(self, cards):
decks = {}
for card in cards:
did = self.database().scalar('select did from cards where id=?', card)
deck = self.decks().get(did)['name']
if deck in decks:
decks[deck].append(card)
else:
decks[deck] = [card]
return decks
@util.api()
def createDeck(self, deck):
try:
self.startEditing()
did = self.decks().id(deck)
finally:
self.stopEditing()
return did
@util.api()
def changeDeck(self, cards, deck):
self.startEditing()
did = self.collection().decks.id(deck)
mod = anki.utils.intTime()
usn = self.collection().usn()
# normal cards
scids = anki.utils.ids2str(cards)
# remove any cards from filtered deck first
self.collection().sched.remFromDyn(cards)
# then move into new deck
self.collection().db.execute('update cards set usn=?, mod=?, did=? where id in ' + scids, usn, mod, did)
self.stopEditing()
@util.api()
def deleteDecks(self, decks, cardsToo=False):
if not cardsToo:
# since f592672fa952260655881a75a2e3c921b2e23857 (2.1.28)
# (see anki$ git log "-Gassert cardsToo")
# you can't delete decks without deleting cards as well.
# however, since 62c23c6816adf912776b9378c008a52bb50b2e8d (2.1.45)
# passing cardsToo to `rem` (long deprecated) won't raise an error!
# this is dangerous, so let's raise our own exception
raise Exception("Since Anki 2.1.28 it's not possible "
"to delete decks without deleting cards as well")
try:
self.startEditing()
decks = filter(lambda d: d in self.deckNames(), decks)
for deck in decks:
did = self.decks().id(deck)
self.decks().rem(did, cardsToo=cardsToo)
finally:
self.stopEditing()
@util.api()
def getDeckConfig(self, deck):
if deck not in self.deckNames():
return False
collection = self.collection()
did = collection.decks.id(deck)
return collection.decks.confForDid(did)
@util.api()
def saveDeckConfig(self, config):
collection = self.collection()
config['id'] = str(config['id'])
config['mod'] = anki.utils.intTime()
config['usn'] = collection.usn()
if int(config['id']) not in [c['id'] for c in collection.decks.all_config()]:
return False
try:
collection.decks.save(config)
collection.decks.updateConf(config)
except:
return False
return True
@util.api()
def setDeckConfigId(self, decks, configId):
configId = int(configId)
for deck in decks:
if not deck in self.deckNames():
return False
collection = self.collection()
for deck in decks:
try:
did = str(collection.decks.id(deck))
deck_dict = aqt.mw.col.decks.decks[did]
deck_dict['conf'] = configId
collection.decks.save(deck_dict)
except:
return False
return True
@util.api()
def cloneDeckConfigId(self, name, cloneFrom='1'):
configId = int(cloneFrom)
collection = self.collection()
if configId not in [c['id'] for c in collection.decks.all_config()]:
return False
config = collection.decks.getConf(configId)
return collection.decks.confId(name, config)
@util.api()
def removeDeckConfigId(self, configId):
collection = self.collection()
if int(configId) not in [c['id'] for c in collection.decks.all_config()]:
return False
collection.decks.remConf(configId)
return True
@util.api()
def getDeckStats(self, decks):
collection = self.collection()
scheduler = self.scheduler()
responseDict = {}
deckIds = list(map(lambda d: collection.decks.id(d), decks))
allDeckNodes = self.collectDeckTreeChildren(scheduler.deck_due_tree())
for deckId, deckNode in allDeckNodes.items():
if deckId in deckIds:
responseDict[deckId] = self.deckStatsToJson(deckNode)
return responseDict
@util.api()
def storeMediaFile(self, filename, data=None, path=None, url=None, skipHash=None, deleteExisting=True):
if not (data or path or url):
raise Exception('You must provide a "data", "path", or "url" field.')
if data:
mediaData = base64.b64decode(data)
elif path:
with open(path, 'rb') as f:
mediaData = f.read()
elif url:
mediaData = util.download(url)
if skipHash is None:
skip = False
else:
m = hashlib.md5()
m.update(mediaData)
skip = skipHash == m.hexdigest()
if skip:
return None
if deleteExisting:
self.deleteMediaFile(filename)
return self.media().writeData(filename, mediaData)
@util.api()
def retrieveMediaFile(self, filename):
filename = os.path.basename(filename)
filename = unicodedata.normalize('NFC', filename)
filename = self.media().stripIllegal(filename)
path = os.path.join(self.media().dir(), filename)
if os.path.exists(path):
with open(path, 'rb') as file:
return base64.b64encode(file.read()).decode('ascii')
return False
@util.api()
def getMediaFilesNames(self, pattern='*'):
path = os.path.join(self.media().dir(), pattern)
return [os.path.basename(p) for p in glob.glob(path)]
@util.api()
def deleteMediaFile(self, filename):
try:
self.media().syncDelete(filename)
except AttributeError:
self.media().trash_files([filename])
@util.api()
def addNote(self, note):
ankiNote = self.createNote(note)
self.addMediaFromNote(ankiNote, note)
collection = self.collection()
self.startEditing()
nCardsAdded = collection.addNote(ankiNote)
if nCardsAdded < 1:
raise Exception('The field values you have provided would make an empty question on all cards.')
collection.autosave()
self.stopEditing()
return ankiNote.id
def addMediaFromNote(self, ankiNote, note):
audioObjectOrList = note.get('audio')
self.addMedia(ankiNote, audioObjectOrList, util.MediaType.Audio)
videoObjectOrList = note.get('video')
self.addMedia(ankiNote, videoObjectOrList, util.MediaType.Video)
pictureObjectOrList = note.get('picture')
self.addMedia(ankiNote, pictureObjectOrList, util.MediaType.Picture)
def addMedia(self, ankiNote, mediaObjectOrList, mediaType):
if mediaObjectOrList is None:
return
if isinstance(mediaObjectOrList, list):
mediaList = mediaObjectOrList
else:
mediaList = [mediaObjectOrList]
for media in mediaList:
if media is not None and len(media['fields']) > 0:
try:
mediaFilename = self.storeMediaFile(media['filename'],
data=media.get('data'),
path=media.get('path'),
url=media.get('url'),
skipHash=media.get('skipHash'),
deleteExisting=media.get('deleteExisting'))
if mediaFilename is not None:
for field in media['fields']:
if field in ankiNote:
if mediaType is util.MediaType.Picture:
ankiNote[field] += u'<img src="{}">'.format(mediaFilename)
elif mediaType is util.MediaType.Audio or mediaType is util.MediaType.Video:
ankiNote[field] += u'[sound:{}]'.format(mediaFilename)
except Exception as e:
errorMessage = str(e).replace('&', '&').replace('<', '<').replace('>', '>')
for field in media['fields']:
if field in ankiNote:
ankiNote[field] += errorMessage
@util.api()
def canAddNote(self, note):
try:
return bool(self.createNote(note))
except:
return False
@util.api()
def updateNoteFields(self, note):
ankiNote = self.getNote(note['id'])
self.startEditing()
for name, value in note['fields'].items():
if name in ankiNote:
ankiNote[name] = value
audioObjectOrList = note.get('audio')
self.addMedia(ankiNote, audioObjectOrList, util.MediaType.Audio)
videoObjectOrList = note.get('video')
self.addMedia(ankiNote, videoObjectOrList, util.MediaType.Video)
pictureObjectOrList = note.get('picture')
self.addMedia(ankiNote, pictureObjectOrList, util.MediaType.Picture)
ankiNote.flush()
self.collection().autosave()
self.stopEditing()
@util.api()
def addTags(self, notes, tags, add=True):
self.startEditing()
self.collection().tags.bulkAdd(notes, tags, add)
self.stopEditing()
@util.api()
def removeTags(self, notes, tags):
return self.addTags(notes, tags, False)
@util.api()
def getTags(self):
return self.collection().tags.all()
@util.api()
def clearUnusedTags(self):
self.collection().tags.registerNotes()
@util.api()
def replaceTags(self, notes, tag_to_replace, replace_with_tag):
self.window().progress.start()
for nid in notes:
try:
note = self.getNote(nid)
except NotFoundError:
continue
if note.hasTag(tag_to_replace):
note.delTag(tag_to_replace)
note.addTag(replace_with_tag)
note.flush()
self.window().requireReset()
self.window().progress.finish()
self.window().reset()
@util.api()
def replaceTagsInAllNotes(self, tag_to_replace, replace_with_tag):
self.window().progress.start()
collection = self.collection()
for nid in collection.db.list('select id from notes'):
note = self.getNote(nid)
if note.hasTag(tag_to_replace):
note.delTag(tag_to_replace)
note.addTag(replace_with_tag)
note.flush()
self.window().requireReset()
self.window().progress.finish()
self.window().reset()
@util.api()
def setEaseFactors(self, cards, easeFactors):
couldSetEaseFactors = []
for i, card in enumerate(cards):
try:
ankiCard = self.getCard(card)
except NotFoundError:
couldSetEaseFactors.append(False)
continue
couldSetEaseFactors.append(True)
ankiCard.factor = easeFactors[i]
ankiCard.flush()
return couldSetEaseFactors
@util.api()
def setSpecificValueOfCard(self, card, keys,
newValues, warning_check=False):
if isinstance(card, list):
print("card has to be int, not list")
return False
if not isinstance(keys, list) or not isinstance(newValues, list):
print("keys and newValues have to be lists.")
return False
if len(newValues) != len(keys):
print("Invalid list lengths.")
return False
for key in keys:
if key in ["did", "id", "ivl", "lapses", "left", "mod", "nid",
"odid", "odue", "ord", "queue", "reps", "type", "usn"]:
if warning_check is False:
return False
result = []
try:
ankiCard = self.getCard(card)
for i, key in enumerate(keys):
setattr(ankiCard, key, newValues[i])
ankiCard.flush()
result.append(True)
except Exception as e:
result.append([False, str(e)])
return result
@util.api()
def getEaseFactors(self, cards):
easeFactors = []
for card in cards:
try:
ankiCard = self.getCard(card)
except NotFoundError:
easeFactors.append(None)
continue
easeFactors.append(ankiCard.factor)
return easeFactors
@util.api()
def suspend(self, cards, suspend=True):
for card in cards:
if self.suspended(card) == suspend:
cards.remove(card)
if len(cards) == 0:
return False
scheduler = self.scheduler()
self.startEditing()
if suspend:
scheduler.suspendCards(cards)
else:
scheduler.unsuspendCards(cards)
self.stopEditing()
return True
@util.api()
def unsuspend(self, cards):
self.suspend(cards, False)
@util.api()
def suspended(self, card):
card = self.getCard(card)
return card.queue == -1
@util.api()
def areSuspended(self, cards):
suspended = []
for card in cards:
try:
suspended.append(self.suspended(card))
except NotFoundError:
suspended.append(None)
return suspended
@util.api()
def areDue(self, cards):
due = []
for card in cards:
if self.findCards('cid:{} is:new'.format(card)):
due.append(True)
else:
date, ivl = self.collection().db.all('select id/1000.0, ivl from revlog where cid = ?', card)[-1]
if ivl >= -1200:
due.append(bool(self.findCards('cid:{} is:due'.format(card))))
else:
due.append(date - ivl <= time.time())
return due
@util.api()
def getIntervals(self, cards, complete=False):
intervals = []
for card in cards:
if self.findCards('cid:{} is:new'.format(card)):
intervals.append(0)
else:
interval = self.collection().db.list('select ivl from revlog where cid = ?', card)
if not complete:
interval = interval[-1]
intervals.append(interval)
return intervals
@util.api()
def modelNames(self):
return self.collection().models.allNames()
@util.api()
def createModel(self, modelName, inOrderFields, cardTemplates, css = None, isCloze = False):
# https://github.com/dae/anki/blob/b06b70f7214fb1f2ce33ba06d2b095384b81f874/anki/stdmodels.py
if len(inOrderFields) == 0:
raise Exception('Must provide at least one field for inOrderFields')
if len(cardTemplates) == 0:
raise Exception('Must provide at least one card for cardTemplates')
if modelName in self.collection().models.allNames():
raise Exception('Model name already exists')
collection = self.collection()
mm = collection.models
# Generate new Note
m = mm.new(modelName)
if isCloze:
m['type'] = MODEL_CLOZE
# Create fields and add them to Note
for field in inOrderFields:
fm = mm.newField(field)
mm.addField(m, fm)
# Add shared css to model if exists. Use default otherwise
if (css is not None):
m['css'] = css
# Generate new card template(s)
cardCount = 1
for card in cardTemplates:
cardName = 'Card ' + str(cardCount)
if 'Name' in card:
cardName = card['Name']
t = mm.newTemplate(cardName)
cardCount += 1
t['qfmt'] = card['Front']
t['afmt'] = card['Back']
mm.addTemplate(m, t)
mm.add(m)
return m
@util.api()
def modelNamesAndIds(self):
models = {}
for model in self.modelNames():
models[model] = int(self.collection().models.byName(model)['id'])
return models
@util.api()
def modelNameFromId(self, modelId):
model = self.collection().models.get(modelId)
if model is None:
raise Exception('model was not found: {}'.format(modelId))
else:
return model['name']
@util.api()
def modelFieldNames(self, modelName):
model = self.collection().models.byName(modelName)
if model is None:
raise Exception('model was not found: {}'.format(modelName))
else:
return [field['name'] for field in model['flds']]
@util.api()
def modelFieldsOnTemplates(self, modelName):
model = self.collection().models.byName(modelName)
if model is None:
raise Exception('model was not found: {}'.format(modelName))
templates = {}
for template in model['tmpls']:
fields = []
for side in ['qfmt', 'afmt']:
fieldsForSide = []
# based on _fieldsOnTemplate from aqt/clayout.py
matches = re.findall('{{[^#/}]+?}}', template[side])
for match in matches:
# remove braces and modifiers
match = re.sub(r'[{}]', '', match)
match = match.split(':')[-1]
# for the answer side, ignore fields present on the question side + the FrontSide field
if match == 'FrontSide' or side == 'afmt' and match in fields[0]:
continue
fieldsForSide.append(match)
fields.append(fieldsForSide)
templates[template['name']] = fields
return templates
@util.api()
def modelTemplates(self, modelName):
model = self.collection().models.byName(modelName)
if model is None:
raise Exception('model was not found: {}'.format(modelName))
templates = {}
for template in model['tmpls']:
templates[template['name']] = {'Front': template['qfmt'], 'Back': template['afmt']}
return templates
@util.api()
def modelStyling(self, modelName):
model = self.collection().models.byName(modelName)
if model is None:
raise Exception('model was not found: {}'.format(modelName))
return {'css': model['css']}
@util.api()
def updateModelTemplates(self, model):
models = self.collection().models
ankiModel = models.byName(model['name'])
if ankiModel is None:
raise Exception('model was not found: {}'.format(model['name']))
templates = model['templates']
for ankiTemplate in ankiModel['tmpls']:
template = templates.get(ankiTemplate['name'])
if template:
qfmt = template.get('Front')
if qfmt:
ankiTemplate['qfmt'] = qfmt
afmt = template.get('Back')
if afmt:
ankiTemplate['afmt'] = afmt
self.save_model(models, ankiModel)
@util.api()
def updateModelStyling(self, model):
models = self.collection().models
ankiModel = models.byName(model['name'])
if ankiModel is None:
raise Exception('model was not found: {}'.format(model['name']))
ankiModel['css'] = model['css']
self.save_model(models, ankiModel)
@util.api()
def findAndReplaceInModels(self, modelName, findText, replaceText, front=True, back=True, css=True):
if not modelName:
ankiModel = self.collection().models.allNames()
else:
model = self.collection().models.byName(modelName)
if model is None:
raise Exception('model was not found: {}'.format(modelName))
ankiModel = [modelName]
updatedModels = 0
for model in ankiModel:
model = self.collection().models.byName(model)
checkForText = False
if css and findText in model['css']:
checkForText = True
model['css'] = model['css'].replace(findText, replaceText)
for tmpls in model.get('tmpls'):
if front and findText in tmpls['qfmt']:
checkForText = True
tmpls['qfmt'] = tmpls['qfmt'].replace(findText, replaceText)
if back and findText in tmpls['afmt']:
checkForText = True
tmpls['afmt'] = tmpls['afmt'].replace(findText, replaceText)
self.save_model(self.collection().models, model)
if checkForText:
updatedModels += 1
return updatedModels
@util.api()
def deckNameFromId(self, deckId):
deck = self.collection().decks.get(deckId)
if deck is None:
raise Exception('deck was not found: {}'.format(deckId))
return deck['name']
@util.api()
def findNotes(self, query=None):
if query is None:
return []
return list(map(int, self.collection().findNotes(query)))
@util.api()
def findCards(self, query=None):
if query is None:
return []
return list(map(int, self.collection().findCards(query)))
@util.api()
def cardsInfo(self, cards):
result = []
for cid in cards:
try:
card = self.getCard(cid)
model = card.model()
note = card.note()
fields = {}
for info in model['flds']:
order = info['ord']
name = info['name']
fields[name] = {'value': note.fields[order], 'order': order}
result.append({
'cardId': card.id,
'fields': fields,
'fieldOrder': card.ord,
'question': util.cardQuestion(card),
'answer': util.cardAnswer(card),
'modelName': model['name'],
'ord': card.ord,
'deckName': self.deckNameFromId(card.did),
'css': model['css'],
'factor': card.factor,
#This factor is 10 times the ease percentage,
# so an ease of 310% would be reported as 3100
'interval': card.ivl,
'note': card.nid,
'type': card.type,
'queue': card.queue,
'due': card.due,
'reps': card.reps,
'lapses': card.lapses,
'left': card.left,
'mod': card.mod,
})
except NotFoundError:
# Anki will give a NotFoundError if the card ID does not exist.
# Best behavior is probably to add an 'empty card' to the
# returned result, so that the items of the input and return
# lists correspond.
result.append({})
return result
@util.api()
def cardsModTime(self, cards):
result = []
for cid in cards:
try:
card = self.getCard(cid)
result.append({
'cardId': card.id,
'mod': card.mod,
})
except NotFoundError:
# Anki will give a NotFoundError if the card ID does not exist.
# Best behavior is probably to add an 'empty card' to the
# returned result, so that the items of the input and return
# lists correspond.
result.append({})
return result
@util.api()
def forgetCards(self, cards):
self.startEditing()
scids = anki.utils.ids2str(cards)
self.collection().db.execute('update cards set type=0, queue=0, left=0, ivl=0, due=0, odue=0, factor=0 where id in ' + scids)
self.stopEditing()
@util.api()
def relearnCards(self, cards):
self.startEditing()
scids = anki.utils.ids2str(cards)
self.collection().db.execute('update cards set type=3, queue=1 where id in ' + scids)
self.stopEditing()
@util.api()
def cardReviews(self, deck, startID):
return self.database().all(
'select id, cid, usn, ease, ivl, lastIvl, factor, time, type from revlog ''where id>? and cid in (select id from cards where did=?)',
startID,
self.decks().id(deck)
)
@util.api()
def reloadCollection(self):
self.collection().reset()
@util.api()
def getLatestReviewID(self, deck):
return self.database().scalar(
'select max(id) from revlog where cid in (select id from cards where did=?)',
self.decks().id(deck)
) or 0
@util.api()
def insertReviews(self, reviews):
if len(reviews) > 0:
sql = 'insert into revlog(id,cid,usn,ease,ivl,lastIvl,factor,time,type) values '
for row in reviews:
sql += '(%s),' % ','.join(map(str, row))
sql = sql[:-1]
self.database().execute(sql)
@util.api()
def notesInfo(self, notes):
result = []
for nid in notes:
try:
note = self.getNote(nid)
model = note.model()
fields = {}
for info in model['flds']:
order = info['ord']
name = info['name']
fields[name] = {'value': note.fields[order], 'order': order}
result.append({
'noteId': note.id,
'tags' : note.tags,
'fields': fields,
'modelName': model['name'],
'cards': self.collection().db.list('select id from cards where nid = ? order by ord', note.id)
})
except NotFoundError:
# Anki will give a NotFoundError if the note ID does not exist.
# Best behavior is probably to add an 'empty card' to the
# returned result, so that the items of the input and return
# lists correspond.
result.append({})
return result
@util.api()
def deleteNotes(self, notes):
try:
self.collection().remNotes(notes)
finally:
self.stopEditing()
@util.api()
def removeEmptyNotes(self):
for model in self.collection().models.all():
if self.collection().models.useCount(model) == 0:
self.collection().models.rem(model)
self.window().requireReset()
@util.api()
def cardsToNotes(self, cards):
return self.collection().db.list('select distinct nid from cards where id in ' + anki.utils.ids2str(cards))
@util.api()
def guiBrowse(self, query=None):
browser = aqt.dialogs.open('Browser', self.window())
browser.activateWindow()
if query is not None:
browser.form.searchEdit.lineEdit().setText(query)
if hasattr(browser, 'onSearch'):
browser.onSearch()
else:
browser.onSearchActivated()
return self.findCards(query)
@util.api()
def guiEditNote(self, note):
Edit.open_dialog_and_show_note_with_id(note)
@util.api()
def guiSelectedNotes(self):
(creator, instance) = aqt.dialogs._dialogs['Browser']
if instance is None:
return []
return instance.selectedNotes()
@util.api()
def guiAddCards(self, note=None):
if note is not None:
collection = self.collection()
deck = collection.decks.byName(note['deckName'])
if deck is None:
raise Exception('deck was not found: {}'.format(note['deckName']))
collection.decks.select(deck['id'])
savedMid = deck.pop('mid', None)
model = collection.models.byName(note['modelName'])
if model is None:
raise Exception('model was not found: {}'.format(note['modelName']))
collection.models.setCurrent(model)
collection.models.update(model)
ankiNote = anki.notes.Note(collection, model)
# fill out card beforehand, so we can be sure of the note id
if 'fields' in note:
for name, value in note['fields'].items():
if name in ankiNote:
ankiNote[name] = value
self.addMediaFromNote(ankiNote, note)
if 'tags' in note:
ankiNote.tags = note['tags']
def openNewWindow():
nonlocal ankiNote
addCards = aqt.dialogs.open('AddCards', self.window())
if savedMid:
deck['mid'] = savedMid
addCards.editor.set_note(ankiNote)
addCards.activateWindow()
aqt.dialogs.open('AddCards', self.window())
addCards.setAndFocusNote(addCards.editor.note)
currentWindow = aqt.dialogs._dialogs['AddCards'][1]
if currentWindow is not None:
currentWindow.closeWithCallback(openNewWindow)
else:
openNewWindow()
return ankiNote.id
else:
addCards = aqt.dialogs.open('AddCards', self.window())
addCards.activateWindow()
return addCards.editor.note.id
@util.api()
def guiReviewActive(self):
return self.reviewer().card is not None and self.window().state == 'review'
@util.api()
def guiCurrentCard(self):
if not self.guiReviewActive():
raise Exception('Gui review is not currently active.')
reviewer = self.reviewer()
card = reviewer.card
model = card.model()
note = card.note()
fields = {}
for info in model['flds']:
order = info['ord']
name = info['name']
fields[name] = {'value': note.fields[order], 'order': order}
buttonList = reviewer._answerButtonList()
return {
'cardId': card.id,
'fields': fields,
'fieldOrder': card.ord,
'question': util.cardQuestion(card),
'answer': util.cardAnswer(card),
'buttons': [b[0] for b in buttonList],
'nextReviews': [reviewer.mw.col.sched.nextIvlStr(reviewer.card, b[0], True) for b in buttonList],
'modelName': model['name'],
'deckName': self.deckNameFromId(card.did),
'css': model['css'],
'template': card.template()['name']
}
@util.api()
def guiStartCardTimer(self):
if not self.guiReviewActive():
return False
card = self.reviewer().card
if card is not None:
card.startTimer()
return True
return False
@util.api()
def guiShowQuestion(self):
if self.guiReviewActive():
self.reviewer()._showQuestion()
return True
return False
@util.api()
def guiShowAnswer(self):
if self.guiReviewActive():
self.window().reviewer._showAnswer()
return True
return False
@util.api()
def guiAnswerCard(self, ease):
if not self.guiReviewActive():
return False
reviewer = self.reviewer()
if reviewer.state != 'answer':
return False
if ease <= 0 or ease > self.scheduler().answerButtons(reviewer.card):
return False
reviewer._answerCard(ease)
return True
@util.api()
def guiDeckOverview(self, name):
collection = self.collection()
if collection is not None:
deck = collection.decks.byName(name)
if deck is not None:
collection.decks.select(deck['id'])
self.window().onOverview()
return True
return False
@util.api()
def guiDeckBrowser(self):
self.window().moveToState('deckBrowser')
@util.api()
def guiDeckReview(self, name):
if self.guiDeckOverview(name):
self.window().moveToState('review')
return True
return False
@util.api()
def guiExitAnki(self):
timer = QTimer()
timer.timeout.connect(self.window().close)
timer.start(1000) # 1s should be enough to allow the response to be sent.
@util.api()
def guiCheckDatabase(self):
self.window().onCheckDB()
return True
@util.api()
def addNotes(self, notes):
results = []
for note in notes:
try:
results.append(self.addNote(note))
except:
results.append(None)
return results
@util.api()
def canAddNotes(self, notes):
results = []
for note in notes:
results.append(self.canAddNote(note))
return results
@util.api()
def exportPackage(self, deck, path, includeSched=False):
collection = self.collection()
if collection is not None:
deck = collection.decks.byName(deck)
if deck is not None:
exporter = AnkiPackageExporter(collection)
exporter.did = deck['id']
exporter.includeSched = includeSched
exporter.exportInto(path)
return True
return False
@util.api()
def importPackage(self, path):
collection = self.collection()
if collection is not None:
try:
self.startEditing()
importer = AnkiPackageImporter(collection, path)
importer.run()
except:
self.stopEditing()
raise
else:
self.stopEditing()
return True
return False
@util.api()
def apiReflect(self, scopes=None, actions=None):
if not isinstance(scopes, list):
raise Exception('scopes has invalid value')
if not (actions is None or isinstance(actions, list)):
raise Exception('actions has invalid value')
cls = type(self)
scopes2 = []
result = {'scopes': scopes2}
if 'actions' in scopes:
if actions is None:
actions = dir(cls)
methodNames = []
for methodName in actions:
if not isinstance(methodName, str):
pass
method = getattr(cls, methodName, None)
if method is not None and getattr(method, 'api', False):
methodNames.append(methodName)
scopes2.append('actions')
result['actions'] = methodNames
return result
#
# Entry
#
# when run inside Anki, `__name__` would be either numeric,
# or, if installed via `link.sh`, `AnkiConnectDev`
if __name__ != "plugin":
if platform.system() == "Windows" and anki_version == (2, 1, 50):
util.patch_anki_2_1_50_having_null_stdout_on_windows()
Edit.register_with_anki()
ac = AnkiConnect()
ac.initLogging()
ac.startWebServer()
|