Skip to content

Commit

Permalink
create deck when importing, close #20
Browse files Browse the repository at this point in the history
  • Loading branch information
Clouder0 committed May 23, 2021
1 parent b3c380d commit eaaceff
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 6 deletions.
5 changes: 4 additions & 1 deletion src/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

from NoteType import Cloze, Choices, ListCloze, TableCloze, QA
from helper.genankiHelper import getDeck, exportDeck
from helper.ankiConnectHelper import addNotes
from helper.ankiConnectHelper import addNotes, checkOnline
import config


Expand Down Expand Up @@ -60,6 +60,9 @@ def HandlePost(text):
def main():
print("Starting...")
noteLists = []
if config.output == "" and not checkOnline(): # import into Anki
print("ERROR: failed to connect with Anki Connect.")
sys.exit()
for file in config.file_list:
print("file: " + file)
f = open(file, "r", encoding="utf-8")
Expand Down
29 changes: 24 additions & 5 deletions src/helper/ankiConnectHelper.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,14 @@
import json


def checkOnline():
try:
getDeckNames()
except Exception:
return False
return True


def request(action, **params):
return {"action": action, "params": params, "version": 6}

Expand All @@ -23,7 +31,7 @@ def invoke(action, **params):

def addNote(target, deck, options={"allowDuplicate": True}, retry=True):
try:
invoke("addNote", note={
return invoke("addNote", note={
"deckName": deck,
"modelName": target.model.modelName,
"fields": target.outputfields,
Expand All @@ -32,17 +40,28 @@ def addNote(target, deck, options={"allowDuplicate": True}, retry=True):
}
)
except Exception as e:
if len(e.args) > 0 and "model" in e.args[0] and \
target.model.modelName not in getModelNamesAndIds().keys():
if len(e.args) == 0:
return e
if "model" in e.args[0] and target.model.modelName not in getModelNamesAndIds().keys():
createModel(target.model)
if retry:
addNote(target, deck, options, False)
elif "deck was not found" in e.args[0] and deck not in getDeckNames():
createDeck(deck)
if retry:
return addNote(target, deck, options, False)


def createDeck(deckName):
return invoke("createDeck", deck=deckName)


def getModelNamesAndIds():
return invoke("modelNamesAndIds")


def getDeckNames():
return invoke("deckNames")


def createModel(model):
return invoke("createModel",
modelName=model.modelName,
Expand Down

0 comments on commit eaaceff

Please sign in to comment.