def onImport(mw: AnkiQt) -> None: filt = ";;".join([x[0] for x in importing.importers(mw.col)]) file = getFile(mw, tr.actions_import(), None, key="import", filter=filt) if not file: return file = str(file) head, ext = os.path.splitext(file) ext = ext.lower() if ext == ".anki": showInfo(tr.importing_anki_files_are_from_a_very()) return elif ext == ".anki2": showInfo(tr.importing_anki2_files_are_not_directly_importable()) return importFile(mw, file)
def importFile(mw: AnkiQt, file: str) -> None: importerClass = None done = False for i in importing.importers(mw.col): if done: break for mext in re.findall(r"[( ]?\*\.(.+?)[) ]", i[0]): if file.endswith(f".{mext}"): importerClass = i[1] done = True break if not importerClass: # if no matches, assume TSV importerClass = importing.importers(mw.col)[0][1] importer = importerClass(mw.col, file) # need to show import dialog? if importer.needMapper: # make sure we can load the file first mw.progress.start(immediate=True) try: importer.open() mw.progress.finish() diag = ImportDialog(mw, importer) except UnicodeDecodeError: mw.progress.finish() showUnicodeWarning() return except Exception as e: mw.progress.finish() msg = repr(str(e)) if msg == "'unknownFormat'": showWarning(tr.importing_unknown_file_format()) else: msg = f"{tr.importing_failed_debug_info()}\n" msg += str(traceback.format_exc()) showText(msg) return finally: importer.close() else: # if it's an apkg/zip, first test it's a valid file if isinstance(importer, AnkiPackageImporter): try: z = zipfile.ZipFile(importer.file) z.getinfo("collection.anki2") except: showWarning(invalidZipMsg()) return # we need to ask whether to import/replace; if it's # a colpkg file then the rest of the import process # will happen in setupApkgImport() if not setupApkgImport(mw, importer): return # importing non-colpkg files mw.progress.start(immediate=True) def on_done(future: Future) -> None: mw.progress.finish() try: future.result() except zipfile.BadZipfile: showWarning(invalidZipMsg()) except V2ImportIntoV1: showWarning("""\ To import this deck, please click the Update button at the top of the deck list, then try again.""" ) except Exception as e: err = repr(str(e)) if "invalidFile" in err: msg = tr.importing_invalid_file_please_restore_from_backup( ) showWarning(msg) elif "invalidTempFolder" in err: showWarning(mw.errorHandler.tempFolderMsg()) elif "readonly" in err: showWarning( tr.importing_unable_to_import_from_a_readonly()) else: msg = f"{tr.importing_failed_debug_info()}\n" msg += str(e) showText(msg) else: log = "\n".join(importer.log) if "\n" not in log: tooltip(log) else: showText(log, plain_text_edit=True) mw.reset() mw.taskman.run_in_background(importer.run, on_done)