diff --git a/AnkiConnect.py b/AnkiConnect.py index 6976928..7dca7c1 100644 --- a/AnkiConnect.py +++ b/AnkiConnect.py @@ -89,11 +89,11 @@ def makeStr(data): def download(url): try: resp = web.urlopen(url, timeout=URL_TIMEOUT) - except web.URLError: - return None + except web.URLError as e: + raise Exception('A urlError has occurred for url ' + url + '. Error messages was: ' + e.message) if resp.code != 200: - return None + raise Exception('Return code for url request' + url + 'was not 200. Error code: ' + resp.code) 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.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 @@ -352,7 +354,7 @@ class AnkiBridge: def retrieveMediaFile(self, filename): # based on writeData from anki/media.py filename = os.path.basename(filename) - filename = normalize("NFC", filename) + filename = normalize('NFC', filename) filename = self.media().stripIllegal(filename) path = os.path.join(self.media().dir(), filename) @@ -370,11 +372,11 @@ class AnkiBridge: def addNote(self, params): collection = self.collection() if collection is None: - return + raise Exception('Collection was not found.') note = self.createNote(params) 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: data = download(params.audio.url) @@ -405,15 +407,15 @@ class AnkiBridge: def createNote(self, params): collection = self.collection() if collection is None: - return + raise Exception('Collection was not found.') model = collection.models.byName(params.modelName) if model is None: - return + raise Exception('Model was not found for model: ' + params.modelName) deck = collection.decks.byName(params.deckName) if deck is None: - return + raise Exception('Deck was not found for deck: ' + params.deckName) note = anki.notes.Note(collection, model) note.model()['did'] = deck['id'] @@ -423,17 +425,23 @@ class AnkiBridge: if name in note: 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 def updateNoteFields(self, params): collection = self.collection() if collection is None: - return + raise Exception('Collection was not found.') note = collection.getNote(params['id']) 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(): if name in note: note[name] = value @@ -606,7 +614,7 @@ class AnkiBridge: for match in matches: # remove braces and modifiers 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 if match == 'FrontSide' or side == 'afmt' and match in fields[0]: @@ -744,7 +752,7 @@ class AnkiBridge: }) except TypeError as e: # 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 # lists correspond. result.append({}) @@ -770,11 +778,11 @@ class AnkiBridge: 'fields': fields, 'modelName': model['name'], '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: # 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 # lists correspond. result.append({}) @@ -856,7 +864,7 @@ class AnkiBridge: def guiCurrentCard(self): if not self.guiReviewActive(): - return + raise Exception('Gui review is not currently active.') reviewer = self.reviewer() card = reviewer.card @@ -1112,10 +1120,13 @@ class AnkiConnect: def addNotes(self, notes): results = [] for note in notes: - params = AnkiNoteParams(note) - if params.validate(): - results.append(self.anki.addNote(params)) - else: + try: + params = AnkiNoteParams(note) + if params.validate(): + results.append(self.anki.addNote(params)) + else: + results.append(None) + except Exception: results.append(None) return results