-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcustomPackage.py
79 lines (63 loc) · 2.52 KB
/
customPackage.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import json
import os
import io
import sqlite3
import tempfile
import time
import zipfile
from genanki import Deck
from custom_apkg_col import APKG_COL
from custom_apkg_schema import APKG_SCHEMA
class Package:
def __init__(self, deck_or_decks=None, media_files=None):
if isinstance(deck_or_decks, Deck):
self.decks = [deck_or_decks]
else:
self.decks = deck_or_decks
self.media_files = media_files or []
def get_bytes(self):
dbfile, dbfilename = tempfile.mkstemp()
os.close(dbfile)
conn = sqlite3.connect(dbfilename)
cursor = conn.cursor()
now_ts = int(time.time())
self.write_to_db(cursor, now_ts)
conn.commit()
conn.close()
f = io.BytesIO()
with zipfile.ZipFile(f, "w") as outzip:
outzip.write(dbfilename, "collection.anki2")
media_file_idx_to_path = dict(enumerate(self.media_files))
media_json = {
idx: os.path.basename(path)
for idx, path in media_file_idx_to_path.items()
}
outzip.writestr("media", json.dumps(media_json))
for idx, path in media_file_idx_to_path.items():
outzip.write(path, str(idx))
f.seek(0)
return f
def write_to_db(self, cursor, now_ts):
cursor.executescript(APKG_SCHEMA)
cursor.executescript(APKG_COL)
for deck in self.decks:
deck.write_to_db(cursor, now_ts)
def write_to_collection_from_addon(self):
"""
Write to local collection. *Only usable when running inside an Anki addon!* Only tested on Anki 2.1.
This writes to a temporary file and then calls the code that Anki uses to import packages.
Note: the caller may want to use mw.checkpoint and mw.reset as follows:
# creates a menu item called "Undo Add Notes From MyAddon" after this runs
mw.checkpoint('Add Notes From MyAddon')
# run import
my_package.write_to_collection_from_addon()
# refreshes main view so new deck is visible
mw.reset()
Tip: if your deck has the same name and ID as an existing deck, then the notes will get placed in that deck rather
than a new deck being created.
"""
from aqt import mw # main window
from anki.importing.apkg import AnkiPackageImporter
tmpfilename = tempfile.NamedTemporaryFile(delete=False).name
self.get_bytes(tmpfilename)
AnkiPackageImporter(mw.col, tmpfilename).run()