diff --git a/anki/importing/apkg.py b/anki/importing/apkg.py index 29944790f..877e8a939 100644 --- a/anki/importing/apkg.py +++ b/anki/importing/apkg.py @@ -10,16 +10,27 @@ class AnkiPackageImporter(Anki2Importer): def run(self): # extract the deck from the zip file - z = zipfile.ZipFile(self.file) + self.zip = z = zipfile.ZipFile(self.file) col = z.read("collection.anki2") colpath = tmpfile(suffix=".anki2") open(colpath, "wb").write(col) - # pass it to the anki2 importer self.file = colpath + # we need the media dict in advance, and we'll need a map of fname -> + # number to use during the import + self.nameToNum = {} + for k, v in json.loads(z.read("media")).items(): + self.nameToNum[v] = k + # run anki2 importer Anki2Importer.run(self) - # import media - media = json.loads(z.read("media")) - for c, file in media.items(): + # import static media + for file, c in self.nameToNum.items(): + if not file.startswith("_"): + continue path = os.path.join(self.col.media.dir(), file) if not os.path.exists(path): open(path, "wb").write(z.read(c)) + + def _srcMediaData(self, fname): + if fname in self.nameToNum: + return self.zip.read(self.nameToNum[fname]) + return None diff --git a/tests/support/media.apkg b/tests/support/media.apkg new file mode 100644 index 000000000..2a727f9a2 Binary files /dev/null and b/tests/support/media.apkg differ diff --git a/tests/test_importing.py b/tests/test_importing.py index 59da147e9..17e78bc06 100644 --- a/tests/test_importing.py +++ b/tests/test_importing.py @@ -6,7 +6,7 @@ from anki.upgrade import Upgrader from anki.utils import ids2str from anki.errors import * from anki.importing import Anki1Importer, Anki2Importer, TextImporter, \ - SupermemoXmlImporter, MnemosyneImporter + SupermemoXmlImporter, MnemosyneImporter, AnkiPackageImporter from anki.notes import Note from anki.db import * @@ -50,7 +50,6 @@ def test_anki2(): imp.run() check() assert len(os.listdir(dst.media.dir())) == 1 - #print dst.path def test_anki2_mediadupes(): tmp = getEmptyDeck() @@ -97,7 +96,24 @@ def test_anki2_mediadupes(): n = empty.getNote(empty.db.scalar("select id from notes")) assert "_" in n.fields[0] - #print dst.path +def test_apkg(): + tmp = getEmptyDeck() + apkg = unicode(os.path.join(testDir, "support/media.apkg")) + imp = AnkiPackageImporter(tmp, apkg) + assert os.listdir(tmp.media.dir()) == [] + imp.run() + assert os.listdir(tmp.media.dir()) == ['foo.wav'] + # importing again should be idempotent in terms of media + tmp.remCards(tmp.db.list("select id from cards")) + imp = AnkiPackageImporter(tmp, apkg) + imp.run() + assert os.listdir(tmp.media.dir()) == ['foo.wav'] + # but if the local file has different data, it will rename + tmp.remCards(tmp.db.list("select id from cards")) + open(os.path.join(tmp.media.dir(), "foo.wav"), "w").write("xyz") + imp = AnkiPackageImporter(tmp, apkg) + imp.run() + assert len(os.listdir(tmp.media.dir())) == 2 def test_anki1(): # get the deck path to import