Accept multiple audio files in note creation and update

This commit is contained in:
Andreas Kienle 2020-02-23 11:59:19 +01:00
parent 08109dafbd
commit eafd3c94dd

View File

@ -449,29 +449,8 @@ class AnkiConnect:
def addNote(self, note): def addNote(self, note):
ankiNote = self.createNote(note) ankiNote = self.createNote(note)
audio = note.get('audio') audioObjectOrList = note.get('audio')
if audio is not None and len(audio['fields']) > 0: self.addAudio(ankiNote, audioObjectOrList)
try:
data = util.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:
audioFilename = self.media().writeData(audio['filename'], data)
for field in audio['fields']:
if field in ankiNote:
ankiNote[field] += u'[sound:{}]'.format(audioFilename)
except Exception as e:
errorMessage = str(e).replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
for field in audio['fields']:
if field in ankiNote:
ankiNote[field] += errorMessage
collection = self.collection() collection = self.collection()
self.startEditing() self.startEditing()
@ -484,6 +463,34 @@ class AnkiConnect:
return ankiNote.id return ankiNote.id
def addAudio(self, ankiNote, audioObjectOrList):
if audioObjectOrList is not None:
audioList = audioObjectOrList if isinstance(audioObjectOrList, list) else [audioObjectOrList]
for audio in audioList:
if audio is not None and len(audio['fields']) > 0:
try:
data = util.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:
audioFilename = self.media().writeData(audio['filename'], data)
for field in audio['fields']:
if field in ankiNote:
ankiNote[field] += u'[sound:{}]'.format(audioFilename)
except Exception as e:
errorMessage = str(e).replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
for field in audio['fields']:
if field in ankiNote:
ankiNote[field] += errorMessage
@util.api() @util.api()
def canAddNote(self, note): def canAddNote(self, note):
try: try:
@ -502,6 +509,9 @@ class AnkiConnect:
if name in ankiNote: if name in ankiNote:
ankiNote[name] = value ankiNote[name] = value
audioObjectOrList = note['audio']
self.addAudio(ankiNote, audioObjectOrList)
ankiNote.flush() ankiNote.flush()