-
Notifications
You must be signed in to change notification settings - Fork 12
/
AnkiBridge.py
307 lines (241 loc) · 9.29 KB
/
AnkiBridge.py
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
# Copyright (C) 2016 Alex Yatskov <alex@foosoft.net>
# Author: Alex Yatskov <alex@foosoft.net>
# This is a derivation of the work available here
# https://github.com/FooSoft/anki-connect/
#
# 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/>.
try:
import anki
import aqt
from anki.sync import AnkiRequestsClient
except:
anki = {}
aqt = {}
AnkiRequestsClient = {}
URL_TIMEOUT = 10
import base64
import hashlib
import os
import unicodedata
# This class imports anki and is used to interact with the database
class AnkiBridge:
def __init__(self):
self.x = "test"
### Core methods ###
def addNote(self, note):
ankiNote = self.createNote(note)
audio = note.get('audio')
if audio is not None and len(audio['fields']) > 0:
try:
data = self.download(audio['url'])
skipHash = audio.get('skipHash')
if skipHash is None:
skip = False
else:
m = hashlib.md5()
m.update(data)
skip = skipHash == m.hexdigest()
if not skip:
for field in audio['fields']:
if field in ankiNote:
ankiNote[field] += u'[sound:{}]'.format(audio['filename'])
self.media().writeData(audio['filename'], data)
except Exception as e:
errorMessage = str(e).replace("&", "&").replace("<", "<").replace(">", ">")
for field in audio['fields']:
if field in ankiNote:
ankiNote[field] += errorMessage
collection = self.collection()
self.startEditing()
collection.addNote(ankiNote)
collection.autosave()
self.stopEditing()
return ankiNote.id
def storeMediaFile(self, filename, data):
self.deleteMediaFile(filename)
self.media().writeData(filename, base64.b64decode(data))
def createDeck(self, deck):
try:
self.startEditing()
did = self.decks().id(deck)
finally:
self.stopEditing()
return did
def deckNames(self):
return self.decks().allNames()
def deleteMediaFile(self, filename):
try:
self.media().syncDelete(filename)
except AttributeError:
self.media().trash_files([filename])
### Helper functions ###
def startEditing(self):
self.window().requireReset()
def stopEditing(self):
if self.collection() is not None:
self.window().maybeReset()
def decks(self):
decks = self.collection().decks
if decks is None:
raise Exception('decks are not available')
else:
return decks
def collection(self):
collection = self.window().col
if collection is None:
raise Exception('collection is not available')
else:
return collection
def window(self):
return aqt.mw
# Only works for python3
def download(self, url):
try:
(code, contents) = self.download(url)
except Exception as e:
raise Exception('{} download failed with error {}'.format(url, str(e)))
if code == 200:
return contents
else:
raise Exception('{} download failed with return code {}'.format(url, code))
def media(self):
media = self.collection().media
if media is None:
raise Exception('media is not available')
else:
return media
### Note builder ###
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']
ankiNote.tags = note['tags']
for name, value in note['fields'].items():
if name in ankiNote:
ankiNote[name] = value
allowDuplicate = False
if 'options' in note:
if 'allowDuplicate' in note['options']:
allowDuplicate = note['options']['allowDuplicate']
if type(allowDuplicate) is not bool:
raise Exception('option parameter \'allowDuplicate\' must be boolean')
duplicateOrEmpty = ankiNote.dupeOrEmpty()
if duplicateOrEmpty == 1:
raise Exception('cannot create note because it is empty')
elif duplicateOrEmpty == 2:
if not allowDuplicate:
raise Exception('cannot create note because it is a duplicate')
else:
return ankiNote
elif duplicateOrEmpty == False:
return ankiNote
else:
raise Exception('cannot create note for unknown reason')
# Check if models are present
def modelNames(self):
return self.collection().models.allNames()
def createModel(self, modelName, inOrderFields, cardTemplates, css = None):
# 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(anki.lang._(modelName))
# Create fields and add them to Note
for field in inOrderFields:
fm = mm.newField(anki.lang._(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:
t = mm.newTemplate(anki.lang._('Card ' + str(cardCount)))
cardCount += 1
t['qfmt'] = card['Front']
t['afmt'] = card['Back']
mm.addTemplate(m, t)
mm.add(m)
return m
### Methods used by remote-decks only ###
def deleteNotes(self, noteId):
self.startEditing()
try:
aqt.mw.col.remNotes([noteId])
finally:
self.stopEditing()
def updateNoteFields(self, note):
# showInfo("{}".format(note['id']))
ankiNote = aqt.mw.col.getNote(note['id'])
# showInfo("{}".format(ankiNote))
if ankiNote is None:
raise Exception('note was not found: {}'.format(note['id']))
for name, value in note['fields'].items():
if name in ankiNote:
ankiNote[name] = value
ankiNote.flush()
# Core current method
def getDeckNotes(self, deckName):
cardIds = self._getAnkiCardIdsForDeck(deckName)
# showInfo("{}".format(cardIds))
cards = self._getCardsFromIds(cardIds)
return cards
def _getAnkiCardIdsForDeck(self, deckName):
# TODO should check if deck name is in the correct format
# Make query to Anki
queryTemplate = "'deck:{}'"
query = queryTemplate.format(deckName)
# showInfo("{}".format(query))
ids = self.collection().findNotes(query)
return ids
def _getCardsFromIds(self, AnkiCardsIds):
result = []
for nid in AnkiCardsIds:
# TODO possible error handling
note = self.collection().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)
})
return result
def checkForMediaFile(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):
return True
else:
return False