Last active
April 9, 2016 21:04
-
-
Save rizzomichaelg/b3d201ada818cc8902dd993031f6418a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Monkey patch to fix anki issue where adding a new cloze | |
deletion while a card is in a custom study results in | |
the new card being added to the Default Deck instead of | |
the appropriate one. | |
See Pull Request: https://github.com/dae/anki/pull/121 | |
""" | |
from anki.collection import _Collection, ids2str, maxID, intTime | |
def genCards(self, nids): | |
"Generate cards for non-empty templates, return ids to remove." | |
# build map of (nid,ord) so we don't create dupes | |
snids = ids2str(nids) | |
have = {} | |
dids = {} | |
for id, nid, ord, did, odid in self.db.execute( | |
"select id, nid, ord, did, odid from cards where nid in "+snids): | |
# existing cards | |
if nid not in have: | |
have[nid] = {} | |
have[nid][ord] = id | |
# and their dids | |
if odid != 0: | |
did = odid | |
if nid in dids: | |
if dids[nid] and dids[nid] != did: | |
# cards are in two or more different decks; revert to | |
# model default | |
dids[nid] = None | |
else: | |
# first card or multiple cards in same deck | |
dids[nid] = did | |
# build cards for each note | |
data = [] | |
ts = maxID(self.db) | |
now = intTime() | |
rem = [] | |
usn = self.usn() | |
for nid, mid, flds in self.db.execute( | |
"select id, mid, flds from notes where id in "+snids): | |
model = self.models.get(mid) | |
avail = self.models.availOrds(model, flds) | |
did = dids.get(nid) or model['did'] | |
# add any missing cards | |
for t in self._tmplsFromOrds(model, avail): | |
doHave = nid in have and t['ord'] in have[nid] | |
if not doHave: | |
# check deck is not a cram deck | |
did = t['did'] or did | |
if self.decks.isDyn(did): | |
did = 1 | |
# if the deck doesn't exist, use default instead | |
did = self.decks.get(did)['id'] | |
# we'd like to use the same due# as sibling cards, but we | |
# can't retrieve that quickly, so we give it a new id | |
# instead | |
data.append((ts, nid, did, t['ord'], | |
now, usn, self.nextID("pos"))) | |
ts += 1 | |
# note any cards that need removing | |
if nid in have: | |
for ord, id in have[nid].items(): | |
if ord not in avail: | |
rem.append(id) | |
# bulk update | |
self.db.executemany(""" | |
insert into cards values (?,?,?,?,?,?,0,0,?,0,0,0,0,0,0,0,0,"")""", | |
data) | |
return rem | |
_Collection.genCards = genCards |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment