Exemple #1
0
def createNote(deck, model, fields):
    m = _find_model(model)
    m['did'] = _find_deck(deck)
    
    note = Note(mw.col, m)
    _set_fields(note, fields)
    mw.col.addNote(note)
    
    duplicateOrEmpty = note.dupeOrEmpty()
    if duplicateOrEmpty == 1:
        raise Exception('cannot create note because it is empty')
    elif duplicateOrEmpty == 2:
        key = m['flds'][0]['name']
        value = stripHTMLMedia(fields[key]) if key in fields else ''
        raise DuplicateException('"{0}" note already exists for "{1}"'.format(model, value))
    elif duplicateOrEmpty == False:
        return
    else:
        raise Exception('cannot create note for unknown reason')
Exemple #2
0
 def addNote(self, note: Note) -> Optional[Note]:
     note.model()["did"] = self.deckChooser.selectedId()
     ret = note.dupeOrEmpty()
     problem = None
     if ret == 1:
         problem = tr(TR.ADDING_THE_FIRST_FIELD_IS_EMPTY)
     problem = gui_hooks.add_cards_will_add_note(problem, note)
     if problem is not None:
         showWarning(problem, help=HelpPage.ADDING_CARD_AND_NOTE)
         return None
     if note.model()["type"] == MODEL_CLOZE:
         if not note.cloze_numbers_in_fields():
             if not askUser(tr(TR.ADDING_YOU_HAVE_A_CLOZE_DELETION_NOTE)):
                 return None
     self.mw.col.add_note(note, self.deckChooser.selectedId())
     self.mw.col.clearUndo()
     self.addHistory(note)
     self.previousNote = note
     self.mw.requireReset(reason=ResetReason.AddCardsAddNote, context=self)
     gui_hooks.add_cards_did_add_note(note)
     return note
Exemple #3
0
    def doImport(self):
        logDebug('beginning import')

        currentProfileDeckId = self.currentProfileDeckCombo.itemData(
            self.currentProfileDeckCombo.currentIndex())
        logDebug('current profile deck id %d' % currentProfileDeckId)

        # get the note ids of all selected notes
        noteIds = [
            self.noteListModel.itemFromIndex(idx).data()
            for idx in self.noteListView.selectedIndexes()
        ]

        # clear the selection
        self.noteListView.clearSelection()

        logDebug('importing %d notes' % len(noteIds))

        statSuccess = 0
        statNoMatchingModel = 0
        statDupe = 0

        for nid in noteIds:
            # load the note
            logDebug('import note id %d' % nid)
            otherNote = self.otherProfileCollection.getNote(nid)

            # find the model name of the note
            modelName = otherNote._model['name']
            logDebug('model name %r' % modelName)

            # find a model in current profile that matches the name of model from other profile
            matchingModel = mw.col.models.byName(modelName)
            if matchingModel:
                # TODO: ensure that field map is same between two models (or same length?), otherwise skip or error?
                logDebug('matching model found, id %s' % matchingModel['id'])
            else:
                logDebug('no matching model, copying')
                copiedModel = deepcopy(
                    otherNote._model
                )  # do deep copy just to be safe. model is a dict, but might be nested
                copiedModel['id'] = None
                mw.col.models.add(copiedModel)
                matchingModel = copiedModel

            # create a new note object
            newNote = Note(mw.col, matchingModel)
            logDebug('new note %s %s' % (newNote.id, newNote.mid))

            # set the deck that the note will generate cards into
            newNote.model()['did'] = currentProfileDeckId

            # copy field values into new note object
            newNote.fields = otherNote.fields[:]  # list of strings, so clone it

            # check if note is dupe of existing one
            if newNote.dupeOrEmpty():
                logDebug('dupe')
                statDupe += 1
                continue

            # check if there are any media files referenced by the note
            mediaFiles = self.otherProfileCollection.media.filesInStr(
                otherNote.mid, otherNote.joinedFields())
            logDebug('mediaFiles %s' % (mediaFiles, ))
            for fn in mediaFiles:
                fullfn = os.path.join(self.otherProfileCollection.media.dir(),
                                      fn)

                # referenced media might not exist, in which case we skip it
                if not os.path.exists(fullfn):
                    continue

                logDebug('copying from %s' % fullfn)
                addedFn = mw.col.media.addFile(fullfn)
                # NOTE: addedFn may differ from fn (name conflict, different contents), in which case we need to update the note.
                if addedFn != fn:
                    logDebug('name conflict')
                    newNote.fields = [
                        f.replace(fn, addedFn) for f in newNote.fields
                    ]

            addedCardCount = mw.col.addNote(newNote)

            statSuccess += 1

        if statSuccess:
            mw.requireReset()

        if statSuccess:
            self.statSuccessLabel.setText('%d notes successfully imported' %
                                          statSuccess)
            self.statSuccessLabel.show()
        else:
            self.statSuccessLabel.hide()
        if statNoMatchingModel:
            self.statNoMatchingModelLabel.setText(
                '%d notes failed to import because there is no matching Note Type in the current profile'
                % statNoMatchingModel)
            self.statNoMatchingModelLabel.show()
        else:
            self.statNoMatchingModelLabel.hide()
        if statDupe:
            self.statDupeLabel.setText(
                '%d notes were duplicates, and skipped' % statDupe)
            self.statDupeLabel.show()
        else:
            self.statDupeLabel.hide()