Skip to content

Commit

Permalink
Add apkg import/export on backend (#1743)
Browse files Browse the repository at this point in the history
* Add apkg export on backend

* Filter out missing media-paths at write time

* Make TagMatcher::new() infallible

* Gather export data instead of copying directly

* Revert changes to rslib/src/tags/

* Reuse filename_is_safe/check_filename_safe()

* Accept func to produce MediaIter in export_apkg()

* Only store file folder once in MediaIter

* Use temporary tables for gathering

export_apkg() now accepts a search instead of a deck id. Decks are
gathered according to the matched notes' cards.

* Use schedule_as_new() to reset cards

* ExportData → ExchangeData

* Ignore ascii case when filtering system tags

* search_notes_cards_into_table →

search_cards_of_notes_into_table

* Start on apkg importing on backend

* Fix due dates in days for apkg export

* Refactor import-export/package

- Move media and meta code into appropriate modules.
- Normalize/check for normalization when deserializing media entries.

* Add SafeMediaEntry for deserialized MediaEntries

* Prepare media based on checksums

- Ensure all existing media files are hashed.
- Hash incoming files during preparation to detect conflicts.
- Uniquify names of conflicting files with hash (not notetype id).
- Mark media files as used while importing notes.
- Finally copy used media.

* Handle encoding in `replace_media_refs()`

* Add trait to keep down cow boilerplate

* Add notetypes immediately instaed of preparing

* Move target_col into Context

* Add notes immediately instaed of preparing

* Note id, not guid of conflicting notes

* Add import_decks()

* decks_configs → deck_configs

* Add import_deck_configs()

* Add import_cards(), import_revlog()

* Use dyn instead of generic for media_fn

Otherwise, would have to pass None with type annotation in the default
case.

* Fix signature of import_apkg()

* Fix search_cards_of_notes_into_table()

* Test new functions in text.rs

* Add roundtrip test for apkg (stub)

* Keep source id of imported cards (or skip)

* Keep source ids of imported revlog (or skip)

* Try to keep source ids of imported notes

* Make adding notetype with id undoable

* Wrap apkg import in transaction

* Keep source ids of imported deck configs (or skip)

* Handle card due dates and original due/did

* Fix importing cards/revlog

Card ids are manually uniquified.

* Factor out card importing

* Refactor card and revlog importing

* Factor out card importing

Also handle missing parents .

* Factor out note importing

* Factor out media importing

* Maybe upgrade scheduler of apkg

* Fix parent deck gathering

* Unconditionally import static media

* Fix deck importing edge cases

Test those edge cases, and add some global test helpers.

* Test note importing

* Let import_apkg() take a progress func

* Expand roundtrip apkg test

* Use fat pointer to avoid propogating generics

* Fix progress_fn type

* Expose apkg export/import on backend

* Return note log when importing apkg

* Fix archived collection name on apkg import

* Add CollectionOpWithBackendProgress

* Fix wrong Interrupted Exception being checked

* Add ClosedCollectionOp

* Add note ids to log and strip HTML

* Update progress when checking incoming media too

* Conditionally enable new importing in GUI

* Fix all_checksums() for media import

Entries of deleted files are nulled, not removed.

* Make apkg exporting on backend abortable

* Return number of notes imported from apkg

* Fix exception printing for QueryOp as well

* Add QueryOpWithBackendProgress

Also support backend exporting progress.

* Expose new apkg and colpkg exporting

* Open transaction in insert_data()

Was slowing down exporting by several orders of magnitude.

* Handle zstd-compressed apkg

* Add legacy arg to ExportAnkiPackage

Currently not exposed on the frontend

* Remove unused import in proto file

* Add symlink for typechecking of import_export_pb2

* Avoid kwargs in pb message creation, so typechecking is not lost

Protobuf's behaviour is rather subtle and I had to dig through the docs
to figure it out: set a field on a submessage to automatically assign 
the submessage to the parent, or call SetInParent() to persist a default
version of the field you specified.

* Avoid re-exporting protobuf msgs we only use internally

* Stop after one test failure

mypy often fails much faster than pylint

* Avoid an extra allocation when extracting media checksums

* Update progress after prepare_media() finishes

Otherwise the bulk of the import ends up being shown as "Checked: 0"
in the progress window.

* Show progress of note imports

Note import is the slowest part, so showing progress here makes the UI
feel more responsive.

* Reset filtered decks at import time

Before this change, filtered decks exported with scheduling remained
filtered on import, and maybe_remove_from_filtered_deck() moved cards
into them as their home deck, leading to errors during review.

We may still want to provide a way to preserve filtered decks on import,
but to do that we'll need to ensure we don't rewrite the home decks of
cards, and we'll need to ensure the home decks are included as part of
the import (or give an error if they're not).

https://github.com/ankitects/anki/pull/1743/files#r839346423

* Fix a corner-case where due dates were shifted by a day

This issue existed in the old Python code as well. We need to include
the user's UTC offset in the exported file, or days_elapsed falls back
on the v1 cutoff calculation, which may be a day earlier or later than
the v2 calculation.

* Log conflicting note in remapped nt case

* take_fields() → into_fields()

* Alias `[u8; 20]` with `Sha1Hash`

* Truncate logged fields

* Rework apkg note import tests

- Use macros for more helpful errors.
- Split monolith into unit tests.
- Fix some unknown error with the previous test along the way.
(Was failing after 969484d.)

* Fix sorting of imported decks

Also adjust the test, so it fails without the patch. It was only passing
before, because the parent deck happened to come before the
inconsistently capitalised child alphabetically. But we want all parent
decks to be imported before their child decks, so their children can
adopt their capitalisation.

* target[_id]s → existing_card[_id]s

* export_collection_extracting_media() → ...

export_into_collection_file()

* target_already_exists→card_ordinal_already_exists

* Add search_cards_of_notes_into_table.sql

* Imrove type of apkg export selector/limit

* Remove redundant call to mod_schema()

* Parent tooltips to mw

* Fix a crash when truncating note text

String::truncate() is a bit of a footgun, and I've hit this before
too :-)

* Remove ExportLimit in favour of separate classes

* Remove OpWithBackendProgress and ClosedCollectionOp

Backend progress logic is now in ProgressManager. QueryOp can be used
for running on closed collection.

Also fix aborting of colpkg exports, which slipped through in #1817.

* Tidy up import log

* Avoid QDialog.exec()

* Default to excluding scheuling for deck list deck

* Use IncrementalProgress in whole import_export code

* Compare checksums when importing colpkgs

* Avoid registering changes if hashes are not needed

* ImportProgress::Collection → ImportProgress::File

* Make downgrading apkgs depend on meta version

* Generalise IncrementableProgress

And use it in entire import_export code instead.

* Fix type complexity lint

* Take count_map for IncrementableProgress::get_inner

* Replace import/export env with Shift click

* Accept all args from update() for backend progress

* Pass fields of ProgressUpdate explicitly

* Move update_interval into IncrementableProgress

* Outsource incrementing into Incrementor

* Mutate ProgressUpdate in progress_update callback

* Switch import/export legacy toggle to profile setting

Shift would have been nice, but the existing shortcuts complicate things.
If the user triggers an import with ctrl+shift+i, shift is unlikely to
have been released by the time our code runs, meaning the user accidentally
triggers the new code. We could potentially wait a while before bringing
up the dialog, but then we're forced to guess at how long it will take the
user to release the key.

One alternative would be to use alt instead of shift, but then we need to
trigger our shortcut when that key is pressed as well, and it could
potentially cause a conflict with an add-on that already uses that
combination.

* Show extension in export dialog

* Continue to provide separate options for schema 11+18 colpkg export

* Default to colpkg export when using File>Export

* Improve appearance of combo boxes when switching between apkg/colpkg

+ Deal with long deck names

* Convert newlines to spaces when showing fields from import

Ensures each imported note appears on a separate line

* Don't separate total note count from the other summary lines

This may come down to personal preference, but I feel the other counts
are equally as important, and separating them feels like it makes it
a bit easier to ignore them.

* Fix 'deck not normal' error when importing a filtered deck for the 2nd time

* Fix [Identical] being shown on first import

* Revert "Continue to provide separate options for schema 11+18 colpkg export"

This reverts commit 8f0b2c1.

Will use a different approach

* Move legacy support into a separate exporter option; add to apkg export

* Adjust 'too new' message to also apply to .apkg import case

* Show a better message when attempting to import new apkg into old code

Previously the user could end seeing a message like:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb5 in position 1: invalid start byte

Unfortunately we can't retroactively fix this for older clients.

* Hide legacy support option in older exporting screen

* Reflect change from paths to fnames in type & name

* Make imported decks normal at once

Then skip special casing in update_deck(). Also skip updating
description if new one is empty.

Co-authored-by: Damien Elmes <gpg@ankiweb.net>
  • Loading branch information
RumovZ and dae committed May 2, 2022
1 parent d2ec004 commit 5f9451f
Show file tree
Hide file tree
Showing 74 changed files with 3,612 additions and 444 deletions.
3 changes: 3 additions & 0 deletions .bazelrc
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ test --aspects=@rules_rust//rust:defs.bzl%rust_clippy_aspect --output_groups=+cl
# print output when test fails
test --test_output=errors

# stop after one test failure
test --notest_keep_going

# don't add empty __init__.py files
build --incompatible_default_to_explicit_init_py

Expand Down
3 changes: 2 additions & 1 deletion ftl/core/exporting.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ exporting-anki-deck-package = Anki Deck Package
exporting-cards-in-plain-text = Cards in Plain Text
exporting-collection = collection
exporting-collection-exported = Collection exported.
exporting-colpkg-too-new = Please update to the latest Anki version, then import the .colpkg file again.
exporting-colpkg-too-new = Please update to the latest Anki version, then import the .colpkg/.apkg file again.
exporting-couldnt-save-file = Couldn't save file: { $val }
exporting-export = Export...
exporting-export-format = <b>Export format</b>:
Expand All @@ -14,6 +14,7 @@ exporting-include-html-and-media-references = Include HTML and media references
exporting-include-media = Include media
exporting-include-scheduling-information = Include scheduling information
exporting-include-tags = Include tags
exporting-support-older-anki-versions = Support older Anki versions (slower/larger files)
exporting-notes-in-plain-text = Notes in Plain Text
exporting-selected-notes = Selected Notes
exporting-card-exported =
Expand Down
6 changes: 6 additions & 0 deletions ftl/core/importing.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -78,4 +78,10 @@ importing-processed-media-file =
*[other] Imported { $count } media files
}
importing-importing-collection = Importing collection...
importing-importing-file = Importing file...
importing-failed-to-import-media-file = Failed to import media file: { $debugInfo }
importing-processed-notes =
{ $count ->
[one] Processed { $count } note...
*[other] Processed { $count } notes...
}
37 changes: 37 additions & 0 deletions proto/anki/import_export.proto
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,25 @@ syntax = "proto3";

package anki.import_export;

import "anki/collection.proto";
import "anki/notes.proto";
import "anki/generic.proto";

service ImportExportService {
rpc ImportCollectionPackage(ImportCollectionPackageRequest)
returns (generic.Empty);
rpc ExportCollectionPackage(ExportCollectionPackageRequest)
returns (generic.Empty);
rpc ImportAnkiPackage(ImportAnkiPackageRequest)
returns (ImportAnkiPackageResponse);
rpc ExportAnkiPackage(ExportAnkiPackageRequest) returns (generic.UInt32);
}

message ImportCollectionPackageRequest {
string col_path = 1;
string backup_path = 2;
string media_folder = 3;
string media_db = 4;
}

message ExportCollectionPackageRequest {
Expand All @@ -26,6 +32,37 @@ message ExportCollectionPackageRequest {
bool legacy = 3;
}

message ImportAnkiPackageRequest {
string package_path = 1;
}

message ImportAnkiPackageResponse {
message Note {
notes.NoteId id = 1;
repeated string fields = 2;
}
message Log {
repeated Note new = 1;
repeated Note updated = 2;
repeated Note duplicate = 3;
repeated Note conflicting = 4;
}
collection.OpChanges changes = 1;
Log log = 2;
}

message ExportAnkiPackageRequest {
string out_path = 1;
bool with_scheduling = 2;
bool with_media = 3;
bool legacy = 4;
oneof selector {
generic.Empty whole_collection = 5;
int64 deck_id = 6;
notes.NoteIds note_ids = 7;
}
}

message PackageMetadata {
enum Version {
VERSION_UNKNOWN = 0;
Expand Down
1 change: 1 addition & 0 deletions pylib/.pylintrc
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ ignored-classes=
CustomStudyRequest,
Cram,
ScheduleCardsAsNewRequest,
ExportAnkiPackageRequest,

[REPORTS]
output-format=colorized
Expand Down
68 changes: 56 additions & 12 deletions pylib/anki/collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
collection_pb2,
config_pb2,
generic_pb2,
import_export_pb2,
links_pb2,
search_pb2,
stats_pb2,
Expand All @@ -32,6 +33,7 @@
BrowserRow = search_pb2.BrowserRow
BrowserColumns = search_pb2.BrowserColumns
StripHtmlMode = card_rendering_pb2.StripHtmlRequest
ImportLogWithChanges = import_export_pb2.ImportAnkiPackageResponse

import copy
import os
Expand Down Expand Up @@ -90,6 +92,19 @@ class LegacyCheckpoint:
LegacyUndoResult = Union[None, LegacyCheckpoint, LegacyReviewUndo]


@dataclass
class DeckIdLimit:
deck_id: DeckId


@dataclass
class NoteIdsLimit:
note_ids: Sequence[NoteId]


ExportLimit = Union[DeckIdLimit, NoteIdsLimit, None]


class Collection(DeprecatedNamesMixin):
sched: V1Scheduler | V2Scheduler | V3Scheduler

Expand Down Expand Up @@ -259,14 +274,6 @@ def close_for_full_sync(self) -> None:
self._clear_caches()
self.db = None

def export_collection(
self, out_path: str, include_media: bool, legacy: bool
) -> None:
self.close_for_full_sync()
self._backend.export_collection_package(
out_path=out_path, include_media=include_media, legacy=legacy
)

def rollback(self) -> None:
self._clear_caches()
self.db.rollback()
Expand Down Expand Up @@ -321,6 +328,15 @@ def usn(self) -> int:
else:
return -1

def legacy_checkpoint_pending(self) -> bool:
return (
self._have_outstanding_checkpoint()
and time.time() - self._last_checkpoint_at < 300
)

# Import/export
##########################################################################

def create_backup(
self,
*,
Expand Down Expand Up @@ -353,12 +369,40 @@ def await_backup_completion(self) -> None:
"Throws if backup creation failed."
self._backend.await_backup_completion()

def legacy_checkpoint_pending(self) -> bool:
return (
self._have_outstanding_checkpoint()
and time.time() - self._last_checkpoint_at < 300
def export_collection_package(
self, out_path: str, include_media: bool, legacy: bool
) -> None:
self.close_for_full_sync()
self._backend.export_collection_package(
out_path=out_path, include_media=include_media, legacy=legacy
)

def import_anki_package(self, path: str) -> ImportLogWithChanges:
return self._backend.import_anki_package(package_path=path)

def export_anki_package(
self,
*,
out_path: str,
limit: ExportLimit,
with_scheduling: bool,
with_media: bool,
legacy_support: bool,
) -> int:
request = import_export_pb2.ExportAnkiPackageRequest(
out_path=out_path,
with_scheduling=with_scheduling,
with_media=with_media,
legacy=legacy_support,
)
if isinstance(limit, DeckIdLimit):
request.deck_id = limit.deck_id
elif isinstance(limit, NoteIdsLimit):
request.note_ids.note_ids.extend(limit.note_ids)
else:
request.whole_collection.SetInParent()
return self._backend.export_anki_package(request)

# Object helpers
##########################################################################

Expand Down
2 changes: 1 addition & 1 deletion pylib/anki/exporting.py
Original file line number Diff line number Diff line change
Expand Up @@ -446,7 +446,7 @@ def progress() -> None:
time.sleep(0.1)

threading.Thread(target=progress).start()
self.col.export_collection(path, self.includeMedia, self.LEGACY)
self.col.export_collection_package(path, self.includeMedia, self.LEGACY)


class AnkiCollectionPackage21bExporter(AnkiCollectionPackageExporter):
Expand Down
1 change: 1 addition & 0 deletions pylib/anki/import_export_pb2.pyi
4 changes: 4 additions & 0 deletions pylib/anki/importing/anki2.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ class V2ImportIntoV1(Exception):
pass


class MediaMapInvalid(Exception):
pass


class Anki2Importer(Importer):

needMapper = False
Expand Down
8 changes: 6 additions & 2 deletions pylib/anki/importing/apkg.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import zipfile
from typing import Any, Optional

from anki.importing.anki2 import Anki2Importer
from anki.importing.anki2 import Anki2Importer, MediaMapInvalid
from anki.utils import tmpfile


Expand All @@ -36,7 +36,11 @@ def run(self) -> None: # type: ignore
# number to use during the import
self.nameToNum = {}
dir = self.col.media.dir()
for k, v in list(json.loads(z.read("media").decode("utf8")).items()):
try:
media_dict = json.loads(z.read("media").decode("utf8"))
except Exception as exc:
raise MediaMapInvalid() from exc
for k, v in list(media_dict.items()):
path = os.path.abspath(os.path.join(dir, v))
if os.path.commonprefix([path, dir]) != dir:
raise Exception("Invalid file")
Expand Down
11 changes: 8 additions & 3 deletions qt/aqt/browser/browser.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@
from anki.utils import is_mac
from aqt import AnkiQt, gui_hooks
from aqt.editor import Editor
from aqt.exporting import ExportDialog
from aqt.exporting import ExportDialog as LegacyExportDialog
from aqt.import_export.exporting import ExportDialog
from aqt.operations.card import set_card_deck, set_card_flag
from aqt.operations.collection import redo, undo
from aqt.operations.note import remove_notes
Expand Down Expand Up @@ -792,8 +793,12 @@ def suspend_selected_cards(self, checked: bool) -> None:
@no_arg_trigger
@skip_if_selection_is_empty
def _on_export_notes(self) -> None:
cids = self.selectedNotesAsCards()
ExportDialog(self.mw, cids=list(cids))
if self.mw.pm.new_import_export():
nids = self.selected_notes()
ExportDialog(self.mw, nids=nids)
else:
cids = self.selectedNotesAsCards()
LegacyExportDialog(self.mw, cids=list(cids))

# Flags & Marking
######################################################################
Expand Down
4 changes: 2 additions & 2 deletions qt/aqt/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from markdown import markdown

import aqt
from anki.errors import DocumentedError, LocalizedError
from anki.errors import DocumentedError, Interrupted, LocalizedError
from aqt.qt import *
from aqt.utils import showText, showWarning, supportText, tr

Expand All @@ -22,7 +22,7 @@

def show_exception(*, parent: QWidget, exception: Exception) -> None:
"Present a caught exception to the user using a pop-up."
if isinstance(exception, InterruptedError):
if isinstance(exception, Interrupted):
# nothing to do
return
help_page = exception.help_page if isinstance(exception, DocumentedError) else None
Expand Down
1 change: 1 addition & 0 deletions qt/aqt/exporting.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ def __init__(
self.col = mw.col.weakref()
self.frm = aqt.forms.exporting.Ui_ExportDialog()
self.frm.setupUi(self)
self.frm.legacy_support.setVisible(False)
self.exporter: Exporter | None = None
self.cids = cids
disable_help_button(self)
Expand Down
29 changes: 25 additions & 4 deletions qt/aqt/forms/exporting.ui
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
<rect>
<x>0</x>
<y>0</y>
<width>295</width>
<height>223</height>
<width>563</width>
<height>245</height>
</rect>
</property>
<property name="windowTitle">
Expand All @@ -30,7 +30,14 @@
</widget>
</item>
<item row="0" column="1">
<widget class="QComboBox" name="format"/>
<widget class="QComboBox" name="format">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QLabel" name="label_2">
Expand All @@ -40,7 +47,11 @@
</widget>
</item>
<item row="1" column="1">
<widget class="QComboBox" name="deck"/>
<widget class="QComboBox" name="deck">
<property name="minimumContentsLength">
<number>50</number>
</property>
</widget>
</item>
</layout>
</item>
Expand Down Expand Up @@ -83,6 +94,16 @@
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="legacy_support">
<property name="text">
<string>exporting_support_older_anki_versions</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</item>
<item>
Expand Down
Empty file.

0 comments on commit 5f9451f

Please sign in to comment.