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=[