Merge pull request #75 from c-okelly/master

Extend error reporting when creating note.
This commit is contained in:
Alex Yatskov 2018-03-12 17:04:36 -07:00 committed by GitHub
commit 1dc9b90796
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -89,11 +89,11 @@ def makeStr(data):
def download(url): def download(url):
try: try:
resp = web.urlopen(url, timeout=URL_TIMEOUT) resp = web.urlopen(url, timeout=URL_TIMEOUT)
except web.URLError: except web.URLError as e:
return None raise Exception('A urlError has occurred for url ' + url + '. Error messages was: ' + e.message)
if resp.code != 200: if resp.code != 200:
return None raise Exception('Return code for url request' + url + 'was not 200. Error code: ' + resp.code)
return resp.read() return resp.read()
@ -337,7 +337,9 @@ class AnkiNoteParams:
type(self.fields) == dict and verifyStringList(list(self.fields.keys())) and verifyStringList(list(self.fields.values())) and type(self.fields) == dict and verifyStringList(list(self.fields.keys())) and verifyStringList(list(self.fields.values())) and
type(self.tags) == list and verifyStringList(self.tags) type(self.tags) == list and verifyStringList(self.tags)
) )
def __str__(self):
return 'DeckName: ' + self.deckName + '. ModelName: ' + self.modelName + '. Fields: ' + str(self.fields) + '. Tags: ' + str(self.tags) + '.'
# #
# AnkiBridge # AnkiBridge
@ -352,7 +354,7 @@ class AnkiBridge:
def retrieveMediaFile(self, filename): def retrieveMediaFile(self, filename):
# based on writeData from anki/media.py # based on writeData from anki/media.py
filename = os.path.basename(filename) filename = os.path.basename(filename)
filename = normalize("NFC", filename) filename = normalize('NFC', filename)
filename = self.media().stripIllegal(filename) filename = self.media().stripIllegal(filename)
path = os.path.join(self.media().dir(), filename) path = os.path.join(self.media().dir(), filename)
@ -370,11 +372,11 @@ class AnkiBridge:
def addNote(self, params): def addNote(self, params):
collection = self.collection() collection = self.collection()
if collection is None: if collection is None:
return raise Exception('Collection was not found.')
note = self.createNote(params) note = self.createNote(params)
if note is None: if note is None:
return raise Exception('Failed to create note from params: ' + str(params))
if params.audio is not None and len(params.audio.fields) > 0: if params.audio is not None and len(params.audio.fields) > 0:
data = download(params.audio.url) data = download(params.audio.url)
@ -405,15 +407,15 @@ class AnkiBridge:
def createNote(self, params): def createNote(self, params):
collection = self.collection() collection = self.collection()
if collection is None: if collection is None:
return raise Exception('Collection was not found.')
model = collection.models.byName(params.modelName) model = collection.models.byName(params.modelName)
if model is None: if model is None:
return raise Exception('Model was not found for model: ' + params.modelName)
deck = collection.decks.byName(params.deckName) deck = collection.decks.byName(params.deckName)
if deck is None: if deck is None:
return raise Exception('Deck was not found for deck: ' + params.deckName)
note = anki.notes.Note(collection, model) note = anki.notes.Note(collection, model)
note.model()['did'] = deck['id'] note.model()['did'] = deck['id']
@ -423,17 +425,23 @@ class AnkiBridge:
if name in note: if name in note:
note[name] = value note[name] = value
if not note.dupeOrEmpty(): # Returns 1 if empty. 2 if duplicate. Otherwise returns False
duplicateOrEmpty = note.dupeOrEmpty()
if duplicateOrEmpty == 1:
raise Exception('Note was empty. Param were: ' + str(params))
elif duplicateOrEmpty == 2:
raise Exception('Note is duplicate of existing note. Params were: ' + str(params))
elif duplicateOrEmpty == False:
return note return note
def updateNoteFields(self, params): def updateNoteFields(self, params):
collection = self.collection() collection = self.collection()
if collection is None: if collection is None:
return raise Exception('Collection was not found.')
note = collection.getNote(params['id']) note = collection.getNote(params['id'])
if note is None: if note is None:
raise Exception("Failed to get note:{}".format(params['id'])) raise Exception('Failed to get note:{}'.format(params['id']))
for name, value in params['fields'].items(): for name, value in params['fields'].items():
if name in note: if name in note:
note[name] = value note[name] = value
@ -606,7 +614,7 @@ class AnkiBridge:
for match in matches: for match in matches:
# remove braces and modifiers # remove braces and modifiers
match = re.sub(r'[{}]', '', match) match = re.sub(r'[{}]', '', match)
match = match.split(":")[-1] match = match.split(':')[-1]
# for the answer side, ignore fields present on the question side + the FrontSide field # 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]: if match == 'FrontSide' or side == 'afmt' and match in fields[0]:
@ -744,7 +752,7 @@ class AnkiBridge:
}) })
except TypeError as e: except TypeError as e:
# Anki will give a TypeError if the card ID does not exist. # Anki will give a TypeError if the card ID does not exist.
# Best behavior is probably to add an "empty card" to the # Best behavior is probably to add an 'empty card' to the
# returned result, so that the items of the input and return # returned result, so that the items of the input and return
# lists correspond. # lists correspond.
result.append({}) result.append({})
@ -770,11 +778,11 @@ class AnkiBridge:
'fields': fields, 'fields': fields,
'modelName': model['name'], 'modelName': model['name'],
'cards': self.collection().db.list( 'cards': self.collection().db.list(
"select id from cards where nid = ? order by ord", note.id) 'select id from cards where nid = ? order by ord', note.id)
}) })
except TypeError as e: except TypeError as e:
# Anki will give a TypeError if the note ID does not exist. # Anki will give a TypeError if the note ID does not exist.
# Best behavior is probably to add an "empty card" to the # Best behavior is probably to add an 'empty card' to the
# returned result, so that the items of the input and return # returned result, so that the items of the input and return
# lists correspond. # lists correspond.
result.append({}) result.append({})
@ -856,7 +864,7 @@ class AnkiBridge:
def guiCurrentCard(self): def guiCurrentCard(self):
if not self.guiReviewActive(): if not self.guiReviewActive():
return raise Exception('Gui review is not currently active.')
reviewer = self.reviewer() reviewer = self.reviewer()
card = reviewer.card card = reviewer.card
@ -1112,10 +1120,13 @@ class AnkiConnect:
def addNotes(self, notes): def addNotes(self, notes):
results = [] results = []
for note in notes: for note in notes:
params = AnkiNoteParams(note) try:
if params.validate(): params = AnkiNoteParams(note)
results.append(self.anki.addNote(params)) if params.validate():
else: results.append(self.anki.addNote(params))
else:
results.append(None)
except Exception:
results.append(None) results.append(None)
return results return results