From fcfa78bba35e0510747e0f28923bc5fd557573f8 Mon Sep 17 00:00:00 2001 From: Arthur Milchior Date: Tue, 11 Feb 2020 16:23:20 -0800 Subject: [PATCH] Hook card_is_being_flushed It often arrives that I want to know when a card is going to be flushed and in this case change it. This could be the case if I want to change the scheduler without implementing a whole scheduler. It simply reads the card history and change interval and due date. It's also the case for the "'trigger -> action' rules", which apply some coded actions when some event occurs. E.g. suspend/unsuspend a sibling when card become mature/is forgotten. --- pylib/anki/cards.py | 3 ++- pylib/anki/hooks.py | 26 ++++++++++++++++++++++++++ pylib/tools/genhooks.py | 5 +++++ 3 files changed, 33 insertions(+), 1 deletion(-) diff --git a/pylib/anki/cards.py b/pylib/anki/cards.py index a31c0fb81..480986ebc 100644 --- a/pylib/anki/cards.py +++ b/pylib/anki/cards.py @@ -84,7 +84,8 @@ class Card: self._render_output = None self._note = None - def _preFlush(self) -> none: + def _preFlush(self) -> None: + hooks.card_will_flush(self) self.mod = intTime() self.usn = self.col.usn() # bug check diff --git a/pylib/anki/hooks.py b/pylib/anki/hooks.py index 1c1627401..d46465e4e 100644 --- a/pylib/anki/hooks.py +++ b/pylib/anki/hooks.py @@ -134,6 +134,32 @@ class _CardOdueWasInvalidHook: card_odue_was_invalid = _CardOdueWasInvalidHook() +class _CardWillFlushHook: + """Allow to change a card before it is added/updated in the database.""" + + _hooks: List[Callable[[Card], None]] = [] + + def append(self, cb: Callable[[Card], None]) -> None: + """(card: Card)""" + self._hooks.append(cb) + + def remove(self, cb: Callable[[Card], None]) -> None: + if cb in self._hooks: + self._hooks.remove(cb) + + def __call__(self, card: Card) -> None: + for hook in self._hooks: + try: + hook(card) + except: + # if the hook fails, remove it + self._hooks.remove(hook) + raise + + +card_will_flush = _CardWillFlushHook() + + class _DeckAddedHook: _hooks: List[Callable[[Dict[str, Any]], None]] = [] diff --git a/pylib/tools/genhooks.py b/pylib/tools/genhooks.py index 0923dba6b..9e124be77 100644 --- a/pylib/tools/genhooks.py +++ b/pylib/tools/genhooks.py @@ -72,6 +72,11 @@ hooks = [ args=["note: Note"], doc="Allow to change a note before it is added/updated in the database.", ), + Hook( + name="card_will_flush", + args=["card: Card"], + doc="Allow to change a card before it is added/updated in the database.", + ), Hook( name="card_did_render", args=[