Merge pull request #444 from Arthur-Milchior/preFlushHooks

Pre flush hooks
This commit is contained in:
Damien Elmes 2020-02-15 12:39:15 +10:00 committed by GitHub
commit 735c3542e1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 71 additions and 10 deletions

View File

@ -84,7 +84,8 @@ class Card:
self._render_output = None self._render_output = None
self._note = None self._note = None
def flush(self) -> None: def _preFlush(self) -> None:
hooks.card_will_flush(self)
self.mod = intTime() self.mod = intTime()
self.usn = self.col.usn() self.usn = self.col.usn()
# bug check # bug check
@ -95,6 +96,9 @@ class Card:
): ):
hooks.card_odue_was_invalid() hooks.card_odue_was_invalid()
assert self.due < 4294967296 assert self.due < 4294967296
def flush(self) -> None:
self._preFlush()
self.col.db.execute( self.col.db.execute(
""" """
insert or replace into cards values insert or replace into cards values
@ -121,16 +125,8 @@ insert or replace into cards values
self.col.log(self) self.col.log(self)
def flushSched(self) -> None: def flushSched(self) -> None:
self.mod = intTime() self._preFlush()
self.usn = self.col.usn()
# bug checks # bug checks
if (
self.queue == QUEUE_TYPE_REV
and self.odue
and not self.col.decks.isDyn(self.did)
):
hooks.card_odue_was_invalid()
assert self.due < 4294967296
self.col.db.execute( self.col.db.execute(
"""update cards set """update cards set
mod=?, usn=?, type=?, queue=?, due=?, ivl=?, factor=?, reps=?, mod=?, usn=?, type=?, queue=?, due=?, ivl=?, factor=?, reps=?,

View File

@ -18,6 +18,7 @@ import decorator
import anki import anki
from anki.cards import Card from anki.cards import Card
from anki.notes import Note
# New hook/filter handling # New hook/filter handling
############################################################################## ##############################################################################
@ -133,6 +134,32 @@ class _CardOdueWasInvalidHook:
card_odue_was_invalid = _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: class _DeckAddedHook:
_hooks: List[Callable[[Dict[str, Any]], None]] = [] _hooks: List[Callable[[Dict[str, Any]], None]] = []
@ -277,6 +304,32 @@ class _NoteTypeAddedHook:
note_type_added = _NoteTypeAddedHook() note_type_added = _NoteTypeAddedHook()
class _NoteWillFlushHook:
"""Allow to change a note before it is added/updated in the database."""
_hooks: List[Callable[[Note], None]] = []
def append(self, cb: Callable[[Note], None]) -> None:
"""(note: Note)"""
self._hooks.append(cb)
def remove(self, cb: Callable[[Note], None]) -> None:
if cb in self._hooks:
self._hooks.remove(cb)
def __call__(self, note: Note) -> None:
for hook in self._hooks:
try:
hook(note)
except:
# if the hook fails, remove it
self._hooks.remove(hook)
raise
note_will_flush = _NoteWillFlushHook()
class _NotesWillBeDeletedHook: class _NotesWillBeDeletedHook:
_hooks: List[Callable[["anki.storage._Collection", List[int]], None]] = [] _hooks: List[Callable[["anki.storage._Collection", List[int]], None]] = []

View File

@ -6,6 +6,7 @@ from __future__ import annotations
from typing import Any, Dict, List, Optional, Tuple from typing import Any, Dict, List, Optional, Tuple
import anki # pylint: disable=unused-import import anki # pylint: disable=unused-import
from anki import hooks
from anki.models import Field, NoteType from anki.models import Field, NoteType
from anki.utils import ( from anki.utils import (
fieldChecksum, fieldChecksum,
@ -202,6 +203,7 @@ insert or replace into notes values (?,?,?,?,?,?,?,?,?,?,?)""",
################################################## ##################################################
def _preFlush(self) -> None: def _preFlush(self) -> None:
hooks.note_will_flush(self)
# have we been added yet? # have we been added yet?
self.newlyAdded = not self.col.db.scalar( self.newlyAdded = not self.col.db.scalar(
"select 1 from cards where nid = ?", self.id "select 1 from cards where nid = ?", self.id

View File

@ -67,6 +67,16 @@ hooks = [
Your add-on can check filter_name to decide whether it should modify Your add-on can check filter_name to decide whether it should modify
field_text or not before returning it.""", field_text or not before returning it.""",
), ),
Hook(
name="note_will_flush",
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( Hook(
name="card_did_render", name="card_did_render",
args=[ args=[