Anki/pylib/anki/exporting.py
RumovZ 5f9451f547
Add apkg import/export on backend (#1743)
* 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 969484de4388d225c9f17d94534b3ba0094c3568.)

* 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 8f0b2c175f.

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>
2022-05-02 21:12:46 +10:00

480 lines
15 KiB
Python

# Copyright: Ankitects Pty Ltd and contributors
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
# pylint: disable=invalid-name
from __future__ import annotations
import json
import os
import re
import shutil
import threading
import time
import unicodedata
import zipfile
from io import BufferedWriter
from typing import Any, Optional, Sequence
from zipfile import ZipFile
from anki import hooks
from anki.cards import CardId
from anki.collection import Collection
from anki.decks import DeckId
from anki.utils import ids2str, namedtmp, split_fields, strip_html
class Exporter:
includeHTML: bool | None = None
ext: Optional[str] = None
includeTags: Optional[bool] = None
includeSched: Optional[bool] = None
includeMedia: Optional[bool] = None
def __init__(
self,
col: Collection,
did: Optional[DeckId] = None,
cids: Optional[list[CardId]] = None,
) -> None:
self.col = col.weakref()
self.did = did
self.cids = cids
@staticmethod
def key(col: Collection) -> str:
return ""
def doExport(self, path) -> None:
raise Exception("not implemented")
def exportInto(self, path: str) -> None:
self._escapeCount = 0
file = open(path, "wb")
self.doExport(file)
file.close()
def processText(self, text: str) -> str:
if self.includeHTML is False:
text = self.stripHTML(text)
text = self.escapeText(text)
return text
def escapeText(self, text: str) -> str:
"Escape newlines, tabs, CSS and quotechar."
# fixme: we should probably quote fields with newlines
# instead of converting them to spaces
text = text.replace("\n", " ")
text = text.replace("\r", "")
text = text.replace("\t", " " * 8)
text = re.sub("(?i)<style>.*?</style>", "", text)
text = re.sub(r"\[\[type:[^]]+\]\]", "", text)
if '"' in text or "'" in text:
text = '"' + text.replace('"', '""') + '"'
return text
def stripHTML(self, text: str) -> str:
# very basic conversion to text
s = text
s = re.sub(r"(?i)<(br ?/?|div|p)>", " ", s)
s = re.sub(r"\[sound:[^]]+\]", "", s)
s = strip_html(s)
s = re.sub(r"[ \n\t]+", " ", s)
s = s.strip()
return s
def cardIds(self) -> Any:
if self.cids is not None:
cids = self.cids
elif not self.did:
cids = self.col.db.list("select id from cards")
else:
cids = self.col.decks.cids(self.did, children=True)
self.count = len(cids)
return cids
# Cards as TSV
######################################################################
class TextCardExporter(Exporter):
ext = ".txt"
includeHTML = True
def __init__(self, col) -> None:
Exporter.__init__(self, col)
@staticmethod
def key(col: Collection) -> str:
return col.tr.exporting_cards_in_plain_text()
def doExport(self, file) -> None:
ids = sorted(self.cardIds())
strids = ids2str(ids)
def esc(s):
# strip off the repeated question in answer if exists
s = re.sub("(?si)^.*<hr id=answer>\n*", "", s)
return self.processText(s)
out = ""
for cid in ids:
c = self.col.get_card(cid)
out += esc(c.question())
out += "\t" + esc(c.answer()) + "\n"
file.write(out.encode("utf-8"))
# Notes as TSV
######################################################################
class TextNoteExporter(Exporter):
ext = ".txt"
includeTags = True
includeHTML = True
def __init__(self, col: Collection) -> None:
Exporter.__init__(self, col)
self.includeID = False
@staticmethod
def key(col: Collection) -> str:
return col.tr.exporting_notes_in_plain_text()
def doExport(self, file: BufferedWriter) -> None:
cardIds = self.cardIds()
data = []
for id, flds, tags in self.col.db.execute(
"""
select guid, flds, tags from notes
where id in
(select nid from cards
where cards.id in %s)"""
% ids2str(cardIds)
):
row = []
# note id
if self.includeID:
row.append(str(id))
# fields
row.extend([self.processText(f) for f in split_fields(flds)])
# tags
if self.includeTags:
row.append(tags.strip())
data.append("\t".join(row))
self.count = len(data)
out = "\n".join(data)
file.write(out.encode("utf-8"))
# Anki decks
######################################################################
# media files are stored in self.mediaFiles, but not exported.
class AnkiExporter(Exporter):
ext = ".anki2"
includeSched: bool | None = False
includeMedia = True
def __init__(self, col: Collection) -> None:
Exporter.__init__(self, col)
@staticmethod
def key(col: Collection) -> str:
return col.tr.exporting_anki_20_deck()
def deckIds(self) -> list[DeckId]:
if self.cids:
return self.col.decks.for_card_ids(self.cids)
elif self.did:
return self.src.decks.deck_and_child_ids(self.did)
else:
return []
def exportInto(self, path: str) -> None:
# sched info+v2 scheduler not compatible w/ older clients
self._v2sched = self.col.sched_ver() != 1 and self.includeSched
# create a new collection at the target
try:
os.unlink(path)
except OSError:
pass
self.dst = Collection(path)
self.src = self.col
# find cards
cids = self.cardIds()
# copy cards, noting used nids
nids = {}
data: list[Sequence] = []
for row in self.src.db.execute(
"select * from cards where id in " + ids2str(cids)
):
# clear flags
row = list(row)
row[-2] = 0
nids[row[1]] = True
data.append(row)
self.dst.db.executemany(
"insert into cards values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", data
)
# notes
strnids = ids2str(list(nids.keys()))
notedata = []
for row in self.src.db.all("select * from notes where id in " + strnids):
# remove system tags if not exporting scheduling info
if not self.includeSched:
row = list(row)
row[5] = self.removeSystemTags(row[5])
notedata.append(row)
self.dst.db.executemany(
"insert into notes values (?,?,?,?,?,?,?,?,?,?,?)", notedata
)
# models used by the notes
mids = self.dst.db.list("select distinct mid from notes where id in " + strnids)
# card history and revlog
if self.includeSched:
data = self.src.db.all("select * from revlog where cid in " + ids2str(cids))
self.dst.db.executemany(
"insert into revlog values (?,?,?,?,?,?,?,?,?)", data
)
else:
# need to reset card state
self.dst.sched.reset_cards(cids)
# models - start with zero
self.dst.mod_schema(check=False)
self.dst.models.remove_all_notetypes()
for m in self.src.models.all():
if int(m["id"]) in mids:
self.dst.models.update(m)
# decks
dids = self.deckIds()
dconfs = {}
for d in self.src.decks.all():
if str(d["id"]) == "1":
continue
if dids and d["id"] not in dids:
continue
if not d["dyn"] and d["conf"] != 1:
if self.includeSched:
dconfs[d["conf"]] = True
if not self.includeSched:
# scheduling not included, so reset deck settings to default
d = dict(d)
d["conf"] = 1
self.dst.decks.update(d)
# copy used deck confs
for dc in self.src.decks.all_config():
if dc["id"] in dconfs:
self.dst.decks.update_config(dc)
# find used media
media = {}
self.mediaDir = self.src.media.dir()
if self.includeMedia:
for row in notedata:
flds = row[6]
mid = row[2]
for file in self.src.media.files_in_str(mid, flds):
# skip files in subdirs
if file != os.path.basename(file):
continue
media[file] = True
if self.mediaDir:
for fname in os.listdir(self.mediaDir):
path = os.path.join(self.mediaDir, fname)
if os.path.isdir(path):
continue
if fname.startswith("_"):
# Scan all models in mids for reference to fname
for m in self.src.models.all():
if int(m["id"]) in mids:
if self._modelHasMedia(m, fname):
media[fname] = True
break
self.mediaFiles = list(media.keys())
self.dst.crt = self.src.crt
# todo: tags?
self.count = self.dst.card_count()
self.postExport()
self.dst.close(downgrade=True)
def postExport(self) -> None:
# overwrite to apply customizations to the deck before it's closed,
# such as update the deck description
pass
def removeSystemTags(self, tags: str) -> Any:
return self.src.tags.rem_from_str("marked leech", tags)
def _modelHasMedia(self, model, fname) -> bool:
# First check the styling
if fname in model["css"]:
return True
# If no reference to fname then check the templates as well
for t in model["tmpls"]:
if fname in t["qfmt"] or fname in t["afmt"]:
return True
return False
# Packaged Anki decks
######################################################################
class AnkiPackageExporter(AnkiExporter):
ext = ".apkg"
def __init__(self, col: Collection) -> None:
AnkiExporter.__init__(self, col)
@staticmethod
def key(col: Collection) -> str:
return col.tr.exporting_anki_deck_package()
def exportInto(self, path: str) -> None:
# open a zip file
z = zipfile.ZipFile(
path, "w", zipfile.ZIP_DEFLATED, allowZip64=True, strict_timestamps=False
)
media = self.doExport(z, path)
# media map
z.writestr("media", json.dumps(media))
z.close()
def doExport(self, z: ZipFile, path: str) -> dict[str, str]: # type: ignore
# export into the anki2 file
colfile = path.replace(".apkg", ".anki2")
AnkiExporter.exportInto(self, colfile)
if not self._v2sched:
z.write(colfile, "collection.anki2")
else:
# prevent older clients from accessing
# pylint: disable=unreachable
self._addDummyCollection(z)
z.write(colfile, "collection.anki21")
# and media
self.prepareMedia()
media = self._exportMedia(z, self.mediaFiles, self.mediaDir)
# tidy up intermediate files
os.unlink(colfile)
p = path.replace(".apkg", ".media.db2")
if os.path.exists(p):
os.unlink(p)
shutil.rmtree(path.replace(".apkg", ".media"))
return media
def _exportMedia(self, z: ZipFile, files: list[str], fdir: str) -> dict[str, str]:
media = {}
for c, file in enumerate(files):
cStr = str(c)
file = hooks.media_file_filter(file)
mpath = os.path.join(fdir, file)
if os.path.isdir(mpath):
continue
if os.path.exists(mpath):
if re.search(r"\.svg$", file, re.IGNORECASE):
z.write(mpath, cStr, zipfile.ZIP_DEFLATED)
else:
z.write(mpath, cStr, zipfile.ZIP_STORED)
media[cStr] = unicodedata.normalize("NFC", file)
hooks.media_files_did_export(c)
return media
def prepareMedia(self) -> None:
# chance to move each file in self.mediaFiles into place before media
# is zipped up
pass
# create a dummy collection to ensure older clients don't try to read
# data they don't understand
def _addDummyCollection(self, zip) -> None:
path = namedtmp("dummy.anki2")
c = Collection(path)
n = c.newNote()
n.fields[0] = "This file requires a newer version of Anki."
c.addNote(n)
c.save()
c.close(downgrade=True)
zip.write(path, "collection.anki2")
os.unlink(path)
# Collection package
######################################################################
class AnkiCollectionPackageExporter(AnkiPackageExporter):
ext = ".colpkg"
verbatim = True
includeSched = None
LEGACY = True
def __init__(self, col):
AnkiPackageExporter.__init__(self, col)
@staticmethod
def key(col: Collection) -> str:
return col.tr.exporting_anki_collection_package()
def exportInto(self, path: str) -> None:
"""Export collection. Caller must re-open afterwards."""
def exporting_media() -> bool:
return any(
hook.__name__ == "exported_media"
for hook in hooks.media_files_did_export._hooks
)
def progress() -> None:
while exporting_media():
progress = self.col._backend.latest_progress()
if progress.HasField("exporting"):
hooks.media_files_did_export(progress.exporting)
time.sleep(0.1)
threading.Thread(target=progress).start()
self.col.export_collection_package(path, self.includeMedia, self.LEGACY)
class AnkiCollectionPackage21bExporter(AnkiCollectionPackageExporter):
LEGACY = False
@staticmethod
def key(_col: Collection) -> str:
return "Anki 2.1.50+ Collection Package"
# Export modules
##########################################################################
def exporters(col: Collection) -> list[tuple[str, Any]]:
def id(obj):
if callable(obj.key):
key_str = obj.key(col)
else:
key_str = obj.key
return (f"{key_str} (*{obj.ext})", obj)
exps = [
id(AnkiCollectionPackageExporter),
id(AnkiCollectionPackage21bExporter),
id(AnkiPackageExporter),
id(TextNoteExporter),
id(TextCardExporter),
]
hooks.exporters_list_created(exps)
return exps