rust: importers take one ImportTarget, and the lib marks imports present

Every importer took (blob_store, doc_store, artifact_store, path, node,
parent, progress) — five clippy::too_many_arguments allows in comics alone,
and a table macro and a comic adapter that only forwarded the seven. They now
take ImportTarget { store, node, parent, progress } and the path; ImportFn is
fn(&ImportTarget, &Path), the directory walk's ImportOne closure receives the
target, and create_collection_node, import_blob_document and import_from_url
take it too. The cbz/cbr dispatch is comics::import_comic_file, which the
comic tree calls directly instead of looking itself up in the table.

SupportedFileType's functions are private behind import/import_directory,
which (like import_file and import_from_url) mark the new document present on
the importing node. Every frontend did that by hand after these calls
(gui import_job::mark_present and Documents, the daemon's mark_present,
Android's ImportBatch), so those copies go. Fixes: the desktop Comics folder
import (import_comic_tree) marked nothing present, and the desktop's and
Android's URL imports didn't either; both now do, as the daemon's did.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Greg ShuflinandClaude Opus 5.5 committed 2026-09-28 18:26:01 -07:00
1 parent 689ad5b276
commit 89a655175d
16 files changed
+380 -935

No files matched your search

+1 -1
View File
@@ -297,7 +297,7 @@ fn cmd_docs_import_list_types() -> Result<()> {
for ty in SUPPORTED_FILE_TYPES {
let filter = ty.filter;
let extensions = filter.extensions.join(", ");
let dir_note = if ty.directory_import.is_some() {
let dir_note = if ty.imports_directories() {
" (also importable as a whole directory of pages)"
} else {
""
+2 -11
View File
@@ -48,7 +48,7 @@ use synchronicity::agents::comics::{
};
use synchronicity::agents::reading::{reading_page, save_reading_page};
use synchronicity::documents::DocumentID;
use synchronicity::documents::import::{COMIC_FILE_TYPES, FileTypeFilter};
use synchronicity::documents::import::{COMIC_FILE_TYPES, FileTypeFilter, ImportTarget};
use synchronicity::jobs::runner::JobRunner;
use synchronicity::node::NodePubkey;
use synchronicity::stores::Store;
@@ -727,16 +727,7 @@ impl ComicsView {
/// a picked file does.
fn import_comic_folder(&mut self, dir: PathBuf, cx: &mut Context<Self>) {
import_job::run(self, dir.display().to_string(), cx, move |store, node, handle| {
import_comic_tree(
&store.blob_store,
&store.doc_store,
&store.artifact_store,
&dir,
node,
None,
Some(handle),
)
.errors
import_comic_tree(ImportTarget::new(store, node), &dir, Some(handle)).errors
});
}
+16 -50
View File
@@ -25,7 +25,8 @@ use synchronicity::content_ledger::{NodeHolding, SubtreeContent, subtree_content
use synchronicity::copy::documents as copy_documents;
use synchronicity::copy::{action, format_bytes};
use synchronicity::documents::import::{
ImportProgress, ImportTotals, create_collection_node, import_directory_tree, import_file,
ImportProgress, ImportTarget, ImportTotals, create_collection_node, import_directory_tree,
import_file,
};
use synchronicity::documents::url_import::import_from_url;
use synchronicity::documents::{DocumentID, DocumentType, PropertyKind, PropertyValue};
@@ -35,7 +36,6 @@ use synchronicity::jobs::{JobKind, JobSubject};
use synchronicity::node::NodePubkey;
use synchronicity::node_status::NodePresence;
use synchronicity::stores::Store;
use synchronicity::stores::blob_store::StoreProgress;
use synchronicity::stores::document::{
DEFAULT_DOCUMENT_PAGE_SIZE, DocumentCursor, DocumentListItem, SearchParams,
};
@@ -886,6 +886,8 @@ impl DocumentsView {
cx,
move || {
let progress = import_job::files_progress(&handle, &paths);
let target =
ImportTarget { progress: Some(&progress), ..ImportTarget::new(&store, node) };
let mut imported = 0usize;
let mut errors: Vec<String> = Vec::new();
for path in &paths {
@@ -894,7 +896,7 @@ impl DocumentsView {
if progress.is_canceled() {
break;
}
match import_one_file(&store, path, None, node, Some(&progress)) {
match import_file(&target, path) {
Ok(Some(_)) => imported += 1,
Ok(None) => {
log::warn!("Skipping unsupported file: {}", path.display())
@@ -943,22 +945,16 @@ impl DocumentsView {
cx,
move || {
let root = std::path::PathBuf::from(&prompt.path);
let target = ImportTarget::new(&store, node);
// When preserving structure, the picked directory itself
// becomes a root-level collection node holding its contents.
let root_parent = if prompt.preserve {
create_collection_node(&store.doc_store, &root, None, node).ok()
} else {
None
};
let root_parent =
prompt.preserve.then(|| create_collection_node(&target, &root).ok()).flatten();
let stats = import_directory_tree(
&store.doc_store,
ImportTarget { parent: root_parent.as_ref(), ..target },
&root,
root_parent.as_ref(),
prompt.preserve,
node,
&mut |path, parent, progress| {
import_one_file(&store, path, parent, node, progress)
},
&mut import_file,
Some(&handle),
);
import_job::finish(handle, &stats.errors);
@@ -993,18 +989,12 @@ impl DocumentsView {
// arrives, so the row counts bytes as they land rather
// than showing a denominator it would have to invent.
let progress = ImportProgress::files(Some(&handle), Some(ImportTotals::file(0)));
let result = import_from_url(
&url,
&store.blob_store,
&store.doc_store,
&store.artifact_store,
node,
None,
Some(&progress),
)
.await
.map(|_| ())
.map_err(|e| format!("URL import failed: {e}"));
let target =
ImportTarget { progress: Some(&progress), ..ImportTarget::new(&store, node) };
let result = import_from_url(&url, &target)
.await
.map(|_| ())
.map_err(|e| format!("URL import failed: {e}"));
progress.tick();
// Finished here rather than after the await: the job is
// also this task's progress sink, so it is borrowed for
@@ -1499,30 +1489,6 @@ fn load_children(store: &Store, parent_id: &str) -> Result<Vec<DocRow>, String>
.collect()
}
/// Import a single file via the lib's shared dispatch, then mark it present on
/// this node. `Ok(None)` means the file matched no supported type and was skipped.
fn import_one_file(
store: &Store,
path: &std::path::Path,
parent: Option<&DocumentID>,
node: NodePubkey,
progress: Option<&dyn StoreProgress>,
) -> Result<Option<DocumentID>, String> {
let Some(doc_id) = import_file(
&store.blob_store,
&store.doc_store,
&store.artifact_store,
path,
node,
parent,
progress,
)?
else {
return Ok(None);
};
Ok(Some(import_job::mark_present(store, node, doc_id)))
}
// ── Formatting ────────────────────────────────────────────────────────────────
fn icon_for_document_type(doc_type: &DocumentType) -> &'static str {
+12 -48
View File
@@ -7,14 +7,14 @@
//! them ended up not doing it at all: ADR 0011's promise is "live dedup+cancel
//! for everything" on desktop, and an untracked import quietly breaks it.
use std::path::{Path, PathBuf};
use std::path::PathBuf;
use std::sync::Arc;
use gpui::{Context, SharedString};
use synchronicity::copy::busy;
use synchronicity::documents::DocumentID;
use synchronicity::documents::import::{
FileTypeFilter, ImportProgress, ImportTotals, find_supported_type, import_directory_tree,
FileTypeFilter, ImportProgress, ImportTarget, ImportTotals, find_supported_type,
import_directory_tree,
};
use synchronicity::jobs::runner::{JobHandle, JobRunner};
use synchronicity::jobs::{JobKind, JobOrigin, JobSubject};
@@ -78,24 +78,10 @@ pub fn files_label(paths: &[PathBuf]) -> String {
}
}
/// Record that `doc_id`, just imported, is present on this node, so an import
/// from any screen counts toward this node's holdings the way the Documents
/// screen's and Android's always have. Best-effort: a failure is logged and the
/// import stands. Returns `doc_id` so it slots into a `.map`.
pub fn mark_present(store: &Store, node: NodePubkey, doc_id: DocumentID) -> DocumentID {
if let Err(e) = store
.node_doc_status_store
.batch(|tx| store.node_doc_status_store.mark_present(tx, &doc_id, &node))
{
log::error!("Failed to mark document {doc_id} present: {e}");
}
doc_id
}
/// A library screen that imports one file type from its own "Import…" trigger
/// — Comics, Music, PDF, Pictures, Video. What differs between them is which
/// type, and what re-reading afterwards means; the job, the walk, the
/// presence mark and the error line are this module's.
/// type, and what re-reading afterwards means; the job, the walk and the
/// error line are this module's.
pub trait ImportHost: Sized + 'static {
/// The one type this screen imports; anything else picked is skipped.
const FILE_TYPES: FileTypeFilter;
@@ -113,12 +99,13 @@ pub trait ImportHost: Sized + 'static {
/// Import the picked `paths` that are of `V`'s type, as one job, then
/// [`ImportHost::imported`].
pub fn import_files<V: ImportHost>(view: &mut V, paths: Vec<PathBuf>, cx: &mut Context<V>) {
let Some(import) = find_supported_type(V::FILE_TYPES.name).map(|ty| ty.import) else {
let Some(ty) = find_supported_type(V::FILE_TYPES.name) else {
log::error!("No importer is registered for {}", V::FILE_TYPES.name);
return;
};
run(view, files_label(&paths), cx, move |store, node, handle| {
let progress = files_progress(handle, &paths);
let target = ImportTarget { progress: Some(&progress), ..ImportTarget::new(store, node) };
let mut errors = Vec::new();
for path in &paths {
// Canceling stops before the next file; whatever already landed
@@ -127,16 +114,7 @@ pub fn import_files<V: ImportHost>(view: &mut V, paths: Vec<PathBuf>, cx: &mut C
break;
}
if V::FILE_TYPES.matches_path(path)
&& let Err(e) = import(
&store.blob_store,
&store.doc_store,
&store.artifact_store,
path,
node,
None,
Some(&progress),
)
.map(|id| mark_present(store, node, id))
&& let Err(e) = ty.import(&target, path)
{
errors.push(format!("Failed to import {}: {e}", path.display()));
}
@@ -150,31 +128,17 @@ pub fn import_files<V: ImportHost>(view: &mut V, paths: Vec<PathBuf>, cx: &mut C
/// flat — these libraries have no notion of nested collections — as one job,
/// then [`ImportHost::imported`].
pub fn import_folder<V: ImportHost>(view: &mut V, dir: PathBuf, cx: &mut Context<V>) {
let Some(import) = find_supported_type(V::FILE_TYPES.name).map(|ty| ty.import) else {
let Some(ty) = find_supported_type(V::FILE_TYPES.name) else {
log::error!("No importer is registered for {}", V::FILE_TYPES.name);
return;
};
run(view, dir.display().to_string(), cx, move |store, node, handle| {
import_directory_tree(
&store.doc_store,
ImportTarget::new(store, node),
&dir,
None,
false,
node,
&mut |path: &Path, _parent, progress| {
if !V::FILE_TYPES.matches_path(path) {
return Ok(None);
}
import(
&store.blob_store,
&store.doc_store,
&store.artifact_store,
path,
node,
None,
progress,
)
.map(|id| Some(mark_present(store, node, id)))
&mut |target, path| {
V::FILE_TYPES.matches_path(path).then(|| ty.import(target, path)).transpose()
},
Some(handle),
)
+11 -15
View File
@@ -5,13 +5,13 @@
use rusqlite::Transaction;
use crate::documents::import::ImportTarget;
use crate::documents::{
Artifact, ArtifactKind, ArtifactValue, BlobRef, Document, DocumentID, DocumentType,
};
use crate::node::NodePubkey;
use crate::stores::artifact::{ArtifactStore, ArtifactStoreError};
use crate::stores::blob_store::{BlobStore, BlobStoreError, StoreProgress, StoredBlob};
use crate::stores::document::{DocumentStore, DocumentStoreError};
use crate::stores::blob_store::{BlobStore, BlobStoreError, StoredBlob};
use crate::stores::document::DocumentStoreError;
use crate::vault::DEFAULT_VAULT_ID;
/// Why an import that only reads a file and writes the stores failed.
@@ -33,23 +33,17 @@ impl From<rusqlite::Error> for ImportError {
}
}
/// Store `data` as a blob, then create a `doc_type` document under `parent_id`
/// carrying whatever properties `write` adds, with its `PrimaryContent`
/// pointing at the blob.
/// Store `data` as a blob, then create a `doc_type` document under
/// `target.parent` carrying whatever properties `write` adds, with its
/// `PrimaryContent` pointing at the blob.
///
/// The document, its properties, and the artifact are one transaction (both
/// stores live in the same `store.db`), so a failure part-way leaves nothing
/// rather than a document with no content.
#[allow(clippy::too_many_arguments)]
pub(crate) fn import_blob_document<E>(
blob_store: &BlobStore,
doc_store: &DocumentStore,
artifact_store: &ArtifactStore,
target: &ImportTarget,
doc_type: DocumentType,
parent_id: Option<&DocumentID>,
local_node: NodePubkey,
data: &[u8],
progress: Option<&dyn StoreProgress>,
write: impl FnOnce(&Transaction, &DocumentID, &StoredBlob) -> Result<(), E>,
) -> Result<DocumentID, E>
where
@@ -58,8 +52,10 @@ where
+ From<ArtifactStoreError>
+ From<rusqlite::Error>,
{
let stored = blob_store.store_reporting(data, DEFAULT_VAULT_ID, progress)?;
let doc = Document::new(doc_type, parent_id.cloned(), local_node);
let ImportTarget { store, node: local_node, parent, progress } = *target;
let (doc_store, artifact_store) = (&store.doc_store, &store.artifact_store);
let stored = store.blob_store.store_reporting(data, DEFAULT_VAULT_ID, progress)?;
let doc = Document::new(doc_type, parent.cloned(), local_node);
let doc_id = doc.id.clone();
doc_store.batch(|tx| {
doc_store.add_document(tx, doc)?;
+86 -360
View File
@@ -39,7 +39,7 @@ use crate::agents::blob_document::{import_blob_document, load_blob, primary_blob
use crate::agents::pictures::write_image_properties;
use crate::content_fetch::{self, ContentFetchError};
use crate::documents::import::{
COMIC_FILE_TYPES, ImportProgress, ImportWalkStats, create_collection_node, find_supported_type,
COMIC_FILE_TYPES, ImportProgress, ImportTarget, ImportWalkStats, create_collection_node,
};
use crate::documents::{
Artifact, ArtifactKind, ArtifactValue, BlobRef, Document, DocumentAvailability, DocumentID,
@@ -51,7 +51,7 @@ use crate::jobs::runner::JobRunner;
use crate::node::NodePubkey;
use crate::stores::Store;
use crate::stores::artifact::{ArtifactStore, ArtifactStoreError};
use crate::stores::blob_store::{BlobStore, BlobStoreError, StoreProgress};
use crate::stores::blob_store::{BlobStore, BlobStoreError};
use crate::stores::document::{DocumentStore, DocumentStoreError};
use crate::stores::node_content_status::NodeContentStore;
@@ -257,27 +257,28 @@ impl From<rusqlite::Error> for ImportComicError {
/// [`Image`](DocumentType::Image) child per page (in reading order), plus metadata
/// properties on the `Comic` parent. The archive bytes are not retained past this
/// function — only the decoded page images and extracted metadata are.
pub fn import_cbz_file(
blob_store: &BlobStore,
doc_store: &DocumentStore,
artifact_store: &ArtifactStore,
path: &Path,
local_node: NodePubkey,
parent_id: Option<&DocumentID>,
progress: Option<&dyn StoreProgress>,
) -> Result<DocumentID, ImportComicError> {
pub fn import_cbz_file(target: &ImportTarget, path: &Path) -> Result<DocumentID, ImportComicError> {
let data = std::fs::read(path)?;
let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("Untitled");
import_cbz_bytes(
blob_store,
doc_store,
artifact_store,
stem,
&data,
local_node,
parent_id,
progress,
)
import_cbz_bytes(target, stem, &data)
}
/// Import a `.cbz` or `.cbr` file, by its extension.
///
/// `cbr` is an optional feature (unrar's bundled C source isn't worth risking on
/// every build, e.g. the Android NDK cross-compile — see its doc comment in
/// Cargo.toml). When it's off, a `.cbr` falls through to the `.cbz` importer, which
/// reports a clear-enough "not a valid .cbz archive" rather than silently mis-importing
/// it; in practice every real consumer (cli-app, gui-app) enables the feature.
pub fn import_comic_file(
target: &ImportTarget,
path: &Path,
) -> Result<DocumentID, ImportComicError> {
#[cfg(feature = "cbr")]
if path.extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("cbr")) {
return import_cbr_file(target, path);
}
import_cbz_file(target, path)
}
/// Import a `.cbz` archive already read into memory as a new
@@ -288,29 +289,13 @@ pub fn import_cbz_file(
/// already operates on bytes. `file_stem` is the title fallback used
/// when the archive carries no `ComicInfo.xml` `Series`/`Title` (usually the picked file's name
/// without its extension).
#[allow(clippy::too_many_arguments)]
pub fn import_cbz_bytes(
blob_store: &BlobStore,
doc_store: &DocumentStore,
artifact_store: &ArtifactStore,
target: &ImportTarget,
file_stem: &str,
data: &[u8],
local_node: NodePubkey,
parent_id: Option<&DocumentID>,
progress: Option<&dyn StoreProgress>,
) -> Result<DocumentID, ImportComicError> {
let (pages, info) = extract_cbz(data)?;
import_comic_from_pages(
blob_store,
doc_store,
artifact_store,
file_stem,
&info,
pages,
local_node,
parent_id,
progress,
)
import_comic_from_pages(target, file_stem, &info, pages)
}
/// Import a `.cbr` (RAR) file as a new [`Comic`](DocumentType::Comic) document, exactly
@@ -319,28 +304,10 @@ pub fn import_cbz_bytes(
/// discarded, so this never needs to *write* a RAR archive (export, if implemented,
/// would only ever produce a `.cbz`).
#[cfg(feature = "cbr")]
pub fn import_cbr_file(
blob_store: &BlobStore,
doc_store: &DocumentStore,
artifact_store: &ArtifactStore,
path: &Path,
local_node: NodePubkey,
parent_id: Option<&DocumentID>,
progress: Option<&dyn StoreProgress>,
) -> Result<DocumentID, ImportComicError> {
pub fn import_cbr_file(target: &ImportTarget, path: &Path) -> Result<DocumentID, ImportComicError> {
let (pages, info) = extract_cbr_pages(path)?;
let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("Untitled");
import_comic_from_pages(
blob_store,
doc_store,
artifact_store,
stem,
&info,
pages,
local_node,
parent_id,
progress,
)
import_comic_from_pages(target, stem, &info, pages)
}
/// Read every page image and the `ComicInfo.xml` sidecar (if present) out of a `.cbr`
@@ -379,13 +346,8 @@ fn extract_cbr_pages(path: &Path) -> Result<(Vec<Page>, ComicInfo), ImportComicE
/// inside the directory is parsed the same way as a `.cbz`'s embedded sidecar, if
/// present; otherwise the directory's own name is the title fallback.
pub fn import_comic_directory(
blob_store: &BlobStore,
doc_store: &DocumentStore,
artifact_store: &ArtifactStore,
target: &ImportTarget,
path: &Path,
local_node: NodePubkey,
parent_id: Option<&DocumentID>,
progress: Option<&dyn StoreProgress>,
) -> Result<DocumentID, ImportComicError> {
let entries: Vec<(String, PathBuf)> = std::fs::read_dir(path)?
.filter_map(|entry| entry.ok())
@@ -411,17 +373,7 @@ pub fn import_comic_directory(
pages.sort_by(|(a, _), (b, _)| compare_page_names(a, b));
let stem = path.file_name().and_then(|s| s.to_str()).unwrap_or("Untitled");
import_comic_from_pages(
blob_store,
doc_store,
artifact_store,
stem,
&info,
pages,
local_node,
parent_id,
progress,
)
import_comic_from_pages(target, stem, &info, pages)
}
// ── Tree import (manga series) ──────────────────────────────────────────────
@@ -469,30 +421,23 @@ pub fn import_comic_directory(
/// file, and it has no total: which directories *are* chapters is only known
/// as the walk classifies them, so the message counts up ("7 chapters")
/// without a denominator to count towards.
///
/// The document `dir` becomes is marked present on this node, as
/// [`SupportedFileType::import_directory`](crate::documents::import::SupportedFileType::import_directory)
/// marks it for [`import_comic_tree_single`].
pub fn import_comic_tree(
blob_store: &BlobStore,
doc_store: &DocumentStore,
artifact_store: &ArtifactStore,
target: ImportTarget<'_>,
dir: &Path,
local_node: NodePubkey,
parent_id: Option<&DocumentID>,
job: Option<&dyn ProgressReporter>,
) -> ImportWalkStats {
let mut stats = ImportWalkStats::default();
let progress = ImportProgress::chapters(job);
import_comic_tree_inner(
blob_store,
doc_store,
artifact_store,
dir,
parent_id,
local_node,
&progress,
// The walk's own `ImportProgress` is the byte sink too: it is the
// thing already reporting to this job's row.
Some(&progress),
&mut stats,
);
// The walk's own `ImportProgress` is the byte sink too: it is the thing
// already reporting to this job's row.
let target = ImportTarget { progress: Some(&progress), ..target };
if let Some(top) = import_comic_tree_inner(&target, &progress, dir, &mut stats) {
target.mark_present(&top);
}
stats
}
@@ -508,32 +453,14 @@ pub fn import_comic_tree(
/// — so a partially-failed series import isn't silently reported as a full
/// success; `docs list`/the GUI library can be used afterward to see what
/// actually landed.
pub fn import_comic_tree_single(
blob_store: &BlobStore,
doc_store: &DocumentStore,
artifact_store: &ArtifactStore,
dir: &Path,
local_node: NodePubkey,
parent_id: Option<&DocumentID>,
progress: Option<&dyn StoreProgress>,
) -> Result<DocumentID, String> {
pub fn import_comic_tree_single(target: &ImportTarget, dir: &Path) -> Result<DocumentID, String> {
let mut stats = ImportWalkStats::default();
let top = import_comic_tree_inner(
blob_store,
doc_store,
artifact_store,
dir,
parent_id,
local_node,
// `ImportFn`'s signature has nowhere to put a job, and its callers
// (the CLI/daemon's `--type comic`) have neither a reporter to tick nor
// anything to cancel through — but they may still have handed down a
// byte sink, since a series folder is one unit to whoever called this
// and its pages are the only thing that can move a bar inside it.
&ImportProgress::untracked(),
progress,
&mut stats,
);
// `ImportFn`'s signature has nowhere to put a job, and its callers (the
// CLI/daemon's `--type comic`) have neither a reporter to tick nor anything
// to cancel through — but they may still have handed down a byte sink in
// `target`, since a series folder is one unit to whoever called this and
// its pages are the only thing that can move a bar inside it.
let top = import_comic_tree_inner(target, &ImportProgress::untracked(), dir, &mut stats);
if let Some(e) = stats.errors.into_iter().next() {
return Err(e);
}
@@ -546,18 +473,13 @@ pub fn import_comic_tree_single(
/// when `dir` had nothing recognizable in it directly (the public wrapper
/// discards this; [`import_comic_tree_single`] uses it as the single
/// `ImportFn`-shaped result).
#[allow(clippy::too_many_arguments)]
fn import_comic_tree_inner(
blob_store: &BlobStore,
doc_store: &DocumentStore,
artifact_store: &ArtifactStore,
dir: &Path,
parent_id: Option<&DocumentID>,
local_node: NodePubkey,
target: &ImportTarget,
progress: &ImportProgress<'_>,
blob_progress: Option<&dyn StoreProgress>,
dir: &Path,
stats: &mut ImportWalkStats,
) -> Option<DocumentID> {
let (doc_store, local_node) = (&target.store.doc_store, target.node);
if progress.is_canceled() {
return None;
}
@@ -599,16 +521,7 @@ fn import_comic_tree_inner(
// Collection branch below, not just the leaf branch.
if subdirs.is_empty() && archives.is_empty() {
if has_images {
let leaf = import_leaf_directory(
blob_store,
doc_store,
artifact_store,
dir,
parent_id,
local_node,
stats,
blob_progress,
);
let leaf = import_leaf_directory(target, dir, stats);
progress.tick();
return leaf;
}
@@ -616,7 +529,7 @@ fn import_comic_tree_inner(
return None;
}
let collection_id = match create_collection_node(doc_store, dir, parent_id, local_node) {
let collection_id = match create_collection_node(target, dir) {
Ok(id) => id,
Err(e) => {
stats.errors.push(format!("Failed to create collection for {}: {e}", dir.display()));
@@ -624,24 +537,14 @@ fn import_comic_tree_inner(
}
};
apply_order(doc_store, &collection_id, dir_name(dir), local_node, false);
let chapter_target = ImportTarget { parent: Some(&collection_id), ..*target };
// Each branch below may hand back a chapter/sub-collection that already carries an explicit
// reading direction — either inferred from its own `ComicInfo.xml` (see
// [`import_comic_from_pages`]) or bubbled up from *its* children (a nested "Volume N" folder).
// First one found wins and lands on `collection_id`, the series root a reader actually
// consults (see [`propagate_series_direction`]).
if has_images
&& let Some(chapter_id) = import_leaf_directory(
blob_store,
doc_store,
artifact_store,
dir,
Some(&collection_id),
local_node,
stats,
blob_progress,
)
{
if has_images && let Some(chapter_id) = import_leaf_directory(&chapter_target, dir, stats) {
propagate_series_direction(doc_store, &collection_id, &chapter_id, local_node);
progress.tick();
}
@@ -649,16 +552,7 @@ fn import_comic_tree_inner(
if progress.is_canceled() {
return Some(collection_id);
}
if let Some(chapter_id) = import_archive_as_chapter(
blob_store,
doc_store,
artifact_store,
archive,
Some(&collection_id),
local_node,
stats,
blob_progress,
) {
if let Some(chapter_id) = import_archive_as_chapter(&chapter_target, archive, stats) {
propagate_series_direction(doc_store, &collection_id, &chapter_id, local_node);
}
// Ticked whether or not the archive imported: what the user is waiting
@@ -671,17 +565,7 @@ fn import_comic_tree_inner(
// top-level caller needs the single "what did `dir` become" answer —
// except here, where it also carries the sub-collection's reading
// direction (if any) up one more level.
if let Some(child_id) = import_comic_tree_inner(
blob_store,
doc_store,
artifact_store,
subdir,
Some(&collection_id),
local_node,
progress,
blob_progress,
stats,
) {
if let Some(child_id) = import_comic_tree_inner(&chapter_target, progress, subdir, stats) {
propagate_series_direction(doc_store, &collection_id, &child_id, local_node);
}
}
@@ -729,28 +613,14 @@ fn propagate_series_direction(
/// A directory containing only loose page images (no subfolders, no
/// archives) becomes one `Comic` chapter, its `Order`/`ComicNumber` derived
/// from the directory's own name.
#[allow(clippy::too_many_arguments)]
fn import_leaf_directory(
blob_store: &BlobStore,
doc_store: &DocumentStore,
artifact_store: &ArtifactStore,
target: &ImportTarget,
dir: &Path,
parent_id: Option<&DocumentID>,
local_node: NodePubkey,
stats: &mut ImportWalkStats,
progress: Option<&dyn StoreProgress>,
) -> Option<DocumentID> {
match import_comic_directory(
blob_store,
doc_store,
artifact_store,
dir,
local_node,
parent_id,
progress,
) {
match import_comic_directory(target, dir) {
Ok(comic_id) => {
apply_order(doc_store, &comic_id, dir_name(dir), local_node, true);
apply_order(&target.store.doc_store, &comic_id, dir_name(dir), target.node, true);
stats.imported += 1;
Some(comic_id)
}
@@ -766,29 +636,16 @@ fn import_leaf_directory(
/// `Comic` chapter, its `Order`/`ComicNumber` derived from the file's stem
/// (e.g. `"Vol.10 Ch.103"` from `"Vol.10 Ch.103.cbz"`). Reuses the same
/// cbz-vs-cbr dispatch every other single-file import goes through
/// ([`crate::documents::import::find_supported_type`]) rather than
/// duplicating the `cbr`-feature branch here.
#[allow(clippy::too_many_arguments)]
/// ([`import_comic_file`]).
fn import_archive_as_chapter(
blob_store: &BlobStore,
doc_store: &DocumentStore,
artifact_store: &ArtifactStore,
target: &ImportTarget,
path: &Path,
parent_id: Option<&DocumentID>,
local_node: NodePubkey,
stats: &mut ImportWalkStats,
progress: Option<&dyn StoreProgress>,
) -> Option<DocumentID> {
let imported = match find_supported_type(COMIC_FILE_TYPES.name) {
Some(t) => {
(t.import)(blob_store, doc_store, artifact_store, path, local_node, parent_id, progress)
}
None => Err(format!("no importer registered for {}", COMIC_FILE_TYPES.name)),
};
match imported {
match import_comic_file(target, path) {
Ok(comic_id) => {
let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("");
apply_order(doc_store, &comic_id, stem, local_node, true);
apply_order(&target.store.doc_store, &comic_id, stem, target.node, true);
stats.imported += 1;
Some(comic_id)
}
@@ -847,24 +704,19 @@ fn dir_name(dir: &Path) -> &str {
/// parent document and its ordered `Image` page children from already-extracted pages
/// and metadata. `fallback` is the display title used when neither `metadata.series`
/// nor `metadata.title` is set (the archive's file stem, or the directory's name).
#[allow(clippy::too_many_arguments)]
fn import_comic_from_pages(
blob_store: &BlobStore,
doc_store: &DocumentStore,
artifact_store: &ArtifactStore,
target: &ImportTarget,
fallback: &str,
ComicInfo { metadata, pages: page_info }: &ComicInfo,
pages: Vec<Page>,
local_node: NodePubkey,
parent_id: Option<&DocumentID>,
progress: Option<&dyn StoreProgress>,
) -> Result<DocumentID, ImportComicError> {
if pages.is_empty() {
return Err(ImportComicError::NoPages);
}
let title = metadata.display_title(fallback);
let (doc_store, local_node) = (&target.store.doc_store, target.node);
let doc = Document::new(DocumentType::Comic, parent_id.cloned(), local_node);
let doc = Document::new(DocumentType::Comic, target.parent.cloned(), local_node);
let doc_id = doc.id.clone();
doc_store.batch(|tx| {
doc_store.add_document(tx, doc)?;
@@ -912,14 +764,9 @@ fn import_comic_from_pages(
let page_title = Path::new(&name).file_stem().and_then(|s| s.to_str()).unwrap_or(&name);
let info = page_info.get(&(index as u32));
import_blob_document(
blob_store,
doc_store,
artifact_store,
&ImportTarget { parent: Some(&doc_id), ..*target },
DocumentType::Image,
Some(&doc_id),
local_node,
&bytes,
progress,
|tx, page_id, _| {
write_image_properties(doc_store, tx, page_id, page_title, ext, local_node)?;
let set = |kind, value: PropertyValue| {
@@ -1640,7 +1487,7 @@ mod tests {
use crate::stores::node_content_status::ContentKey;
use crate::test_support::{
RecordingJob, TestStore, get_blob_ref, get_document, get_property, get_title,
initialized_store, list_children, list_documents_by_type, node, test_node,
initialized_store, list_children, list_documents_by_type, node, present_on, test_node,
};
use rstest::rstest;
@@ -1780,15 +1627,7 @@ mod tests {
/// [`import_comic_tree`] against a test store, walking to completion (only
/// [`import_comic_tree_stops_when_canceled`] cancels mid-walk).
fn import_tree(store: &TestStore, dir: &Path) -> ImportWalkStats {
import_comic_tree(
&store.blob_store,
&store.doc_store,
&store.artifact_store,
dir,
test_node(),
None,
None,
)
import_comic_tree(ImportTarget::new(store, test_node()), dir, None)
}
/// The canonical three-page fixture shared by every import-source test
@@ -1800,48 +1639,20 @@ mod tests {
fn import_three_page_cbz(store: &TestStore) -> DocumentID {
let cbz = build_cbz(THREE_PAGES, None);
let path = write_cbz(&store.path, "test.cbz", &cbz);
import_cbz_file(
&store.blob_store,
&store.doc_store,
&store.artifact_store,
&path,
test_node(),
None,
None,
)
.unwrap()
import_cbz_file(&ImportTarget::new(store, test_node()), &path).unwrap()
}
/// Import [`THREE_PAGES`] straight from `.cbz` bytes (as the FFI layer's
/// [`import_cbz_bytes`] does), with title stem "test".
fn import_three_page_cbz_bytes(store: &TestStore) -> DocumentID {
let cbz = build_cbz(THREE_PAGES, None);
import_cbz_bytes(
&store.blob_store,
&store.doc_store,
&store.artifact_store,
"test",
&cbz,
test_node(),
None,
None,
)
.unwrap()
import_cbz_bytes(&ImportTarget::new(store, test_node()), "test", &cbz).unwrap()
}
/// Import [`THREE_PAGES`] from a directory named "My Comic".
fn import_three_page_directory(store: &TestStore) -> DocumentID {
let dir = build_comic_dir(&store.path, "My Comic", THREE_PAGES, None);
import_comic_directory(
&store.blob_store,
&store.doc_store,
&store.artifact_store,
&dir,
test_node(),
None,
None,
)
.unwrap()
import_comic_directory(&ImportTarget::new(store, test_node()), &dir).unwrap()
}
/// Assertions shared by every import source for [`THREE_PAGES`]: a Comic
@@ -1934,32 +1745,13 @@ mod tests {
fn import_two_page_cbz_with_sidecar(store: &TestStore) -> DocumentID {
let cbz = build_cbz(&[("01.jpg", b"a"), ("02.jpg", b"b")], Some(SIDECAR_INFO));
let path = write_cbz(&store.path, "test.cbz", &cbz);
import_cbz_file(
&store.blob_store,
&store.doc_store,
&store.artifact_store,
&path,
test_node(),
None,
None,
)
.unwrap()
import_cbz_file(&ImportTarget::new(store, test_node()), &path).unwrap()
}
/// Import a two-page `.cbz` carrying [`SIDECAR_INFO`] straight from bytes.
fn import_two_page_cbz_bytes_with_sidecar(store: &TestStore) -> DocumentID {
let cbz = build_cbz(&[("01.jpg", b"a"), ("02.jpg", b"b")], Some(SIDECAR_INFO));
import_cbz_bytes(
&store.blob_store,
&store.doc_store,
&store.artifact_store,
"unused-stem",
&cbz,
test_node(),
None,
None,
)
.unwrap()
import_cbz_bytes(&ImportTarget::new(store, test_node()), "unused-stem", &cbz).unwrap()
}
/// Import a two-page directory carrying [`SIDECAR_INFO`] as a sidecar file.
@@ -1970,16 +1762,7 @@ mod tests {
&[("01.jpg", b"a"), ("02.jpg", b"b")],
Some(SIDECAR_INFO),
);
import_comic_directory(
&store.blob_store,
&store.doc_store,
&store.artifact_store,
&dir,
test_node(),
None,
None,
)
.unwrap()
import_comic_directory(&ImportTarget::new(store, test_node()), &dir).unwrap()
}
#[rstest]
@@ -2033,16 +1816,7 @@ mod tests {
let cbz = build_cbz(&[("001.jpg", b"a"), ("002.jpg", b"b")], Some(info));
let path = write_cbz(&store.path, "test.cbz", &cbz);
let comic_id = import_cbz_file(
&store.blob_store,
&store.doc_store,
&store.artifact_store,
&path,
test_node(),
None,
None,
)
.unwrap();
let comic_id = import_cbz_file(&ImportTarget::new(&store, test_node()), &path).unwrap();
let pages = list_comic_pages(&store.doc_store, &comic_id).unwrap();
let page0 = comic_page_metadata(&store.doc_store, &pages[0]).unwrap();
@@ -2065,16 +1839,8 @@ mod tests {
None,
);
let comic_id = import_comic_directory(
&store.blob_store,
&store.doc_store,
&store.artifact_store,
&comic_dir,
test_node(),
None,
None,
)
.unwrap();
let comic_id =
import_comic_directory(&ImportTarget::new(&store, test_node()), &comic_dir).unwrap();
let pages = list_comic_pages(&store.doc_store, &comic_id).unwrap();
assert_eq!(pages.len(), 2);
@@ -2092,16 +1858,8 @@ mod tests {
fn import_directory_with_no_pages_errors(#[from(initialized_store)] store: TestStore) {
let comic_dir = build_comic_dir(&store.path, "Empty", &[], None);
let err = import_comic_directory(
&store.blob_store,
&store.doc_store,
&store.artifact_store,
&comic_dir,
test_node(),
None,
None,
)
.unwrap_err();
let err = import_comic_directory(&ImportTarget::new(&store, test_node()), &comic_dir)
.unwrap_err();
assert!(matches!(err, ImportComicError::NoPages));
}
@@ -2121,15 +1879,8 @@ mod tests {
}
let job = RecordingJob::canceling_after(1);
let stats = import_comic_tree(
&store.blob_store,
&store.doc_store,
&store.artifact_store,
&series_dir,
test_node(),
None,
Some(&job),
);
let stats =
import_comic_tree(ImportTarget::new(&store, test_node()), &series_dir, Some(&job));
assert_eq!(stats.imported, 1);
assert_eq!(list_documents_by_type(&store.doc_store, &DocumentType::Comic).len(), 1);
@@ -2154,6 +1905,8 @@ mod tests {
assert_eq!(comics.len(), 1);
assert_eq!(comics[0].parent_id, None);
assert_three_page_import(&store, &comics[0].id);
// The folder's comic is this node's, as a picked file's would be.
assert_eq!(present_on(&store, test_node()), vec![comics[0].id.clone()]);
}
#[rstest]
@@ -2407,16 +2160,7 @@ mod tests {
let cbz = build_cbz(&[("01.jpg", b"a")], Some(info));
let path = write_cbz(&store.path, "test.cbz", &cbz);
let comic_id = import_cbz_file(
&store.blob_store,
&store.doc_store,
&store.artifact_store,
&path,
test_node(),
None,
None,
)
.unwrap();
let comic_id = import_cbz_file(&ImportTarget::new(&store, test_node()), &path).unwrap();
// A standalone import (no wrapping Collection) is its own series root, so the
// inferred direction lands directly on it.
@@ -2434,16 +2178,7 @@ mod tests {
let cbz = build_cbz(&[("01.jpg", b"a")], Some(info));
let path = write_cbz(&store.path, "test.cbz", &cbz);
let comic_id = import_cbz_file(
&store.blob_store,
&store.doc_store,
&store.artifact_store,
&path,
test_node(),
None,
None,
)
.unwrap();
let comic_id = import_cbz_file(&ImportTarget::new(&store, test_node()), &path).unwrap();
assert_eq!(reading_direction(&store.doc_store, &comic_id).unwrap(), None);
}
@@ -2564,16 +2299,7 @@ mod tests {
fn import_sample_cbr(store: &TestStore) -> DocumentID {
let path = store.path.join("test.cbr");
std::fs::write(&path, SAMPLE_CBR).unwrap();
import_cbr_file(
&store.blob_store,
&store.doc_store,
&store.artifact_store,
&path,
test_node(),
None,
None,
)
.unwrap()
import_cbr_file(&ImportTarget::new(store, test_node()), &path).unwrap()
}
#[rstest]
+13 -42
View File
@@ -35,6 +35,7 @@ use crate::agents::streaming::{self, StreamHandle, StreamingError};
use crate::content_fetch;
use crate::copy;
use crate::documents::derived_id::{DerivedKey, Domain};
use crate::documents::import::ImportTarget;
use crate::documents::{
Artifact, ArtifactKind, ArtifactValue, BlobHash, BlobRef, Document, DocumentAvailability,
DocumentID, DocumentType, Edge, EdgeKind, Property, PropertyKind, PropertyValue, Provenance,
@@ -48,8 +49,12 @@ use crate::jobs::runner::JobHandle;
use crate::jobs::runner::JobRunner;
use crate::node::NodePubkey;
use crate::stores::Store;
use crate::stores::artifact::{ArtifactStore, ArtifactStoreError};
use crate::stores::blob_store::{BlobStore, BlobStoreError, StoreProgress};
#[cfg(feature = "multimedia")]
use crate::stores::artifact::ArtifactStore;
use crate::stores::artifact::ArtifactStoreError;
#[cfg(feature = "multimedia")]
use crate::stores::blob_store::BlobStore;
use crate::stores::blob_store::BlobStoreError;
use crate::stores::document::{DocumentStore, DocumentStoreError};
use crate::vault::DEFAULT_VAULT_ID;
@@ -226,38 +231,13 @@ pub fn write_mp3_properties(
Ok(())
}
pub fn import_mp3_file(
blob_store: &BlobStore,
doc_store: &DocumentStore,
artifact_store: &ArtifactStore,
path: &Path,
local_node: NodePubkey,
parent_id: Option<&DocumentID>,
progress: Option<&dyn StoreProgress>,
) -> Result<DocumentID> {
pub fn import_mp3_file(target: &ImportTarget, path: &Path) -> Result<DocumentID> {
let (doc_store, local_node) = (&target.store.doc_store, target.node);
let data = std::fs::read(path)?;
let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("Untitled");
import_blob_document(
blob_store,
doc_store,
artifact_store,
DocumentType::MusicTrack,
parent_id,
local_node,
&data,
progress,
|tx, doc_id, stored| {
write_mp3_properties(
doc_store,
tx,
doc_id,
&data,
stem,
&stored.plaintext_hash,
local_node,
)
},
)
import_blob_document(target, DocumentType::MusicTrack, &data, |tx, doc_id, stored| {
write_mp3_properties(doc_store, tx, doc_id, &data, stem, &stored.plaintext_hash, local_node)
})
}
// ── Tag extraction ────────────────────────────────────────────────────────────
@@ -2329,16 +2309,7 @@ mod tests {
fn import_track(store: &TestStore, name: &str, tag: &Tag) -> DocumentID {
let path = store.path.join(format!("{name}.mp3"));
std::fs::write(&path, mp3_with_tag(tag, 20)).unwrap();
import_mp3_file(
&store.blob_store,
&store.doc_store,
&store.artifact_store,
&path,
test_node(),
None,
None,
)
.unwrap()
import_mp3_file(&ImportTarget::new(store, test_node()), &path).unwrap()
}
fn album_of(store: &TestStore, track_id: &DocumentID) -> Option<DocumentID> {
+8 -33
View File
@@ -10,6 +10,7 @@ use crate::agents::blob_document::{
};
use crate::content_fetch::{self, ContentFetchError};
use crate::copy;
use crate::documents::import::ImportTarget;
use crate::documents::{
BlobRef, DocumentAvailability, DocumentID, DocumentType, PropertyKind, PropertyValue,
Timestamp, document_availability_bulk,
@@ -18,7 +19,7 @@ use crate::jobs::runner::JobRunner;
use crate::node::NodePubkey;
use crate::stores::Store;
use crate::stores::artifact::{ArtifactStore, ArtifactStoreError};
use crate::stores::blob_store::{BlobStore, BlobStoreError, StoreProgress};
use crate::stores::blob_store::{BlobStore, BlobStoreError};
use crate::stores::document::{DocumentStore, DocumentStoreError};
/// The title a PDF imported under `file_name` falls back to when the document
@@ -107,32 +108,15 @@ pub fn write_pdf_properties(
Ok(())
}
pub fn import_pdf_file(
blob_store: &BlobStore,
doc_store: &DocumentStore,
artifact_store: &ArtifactStore,
path: &Path,
local_node: NodePubkey,
parent_id: Option<&DocumentID>,
progress: Option<&dyn StoreProgress>,
) -> Result<DocumentID, ImportError> {
pub fn import_pdf_file(target: &ImportTarget, path: &Path) -> Result<DocumentID, ImportError> {
let (doc_store, local_node) = (&target.store.doc_store, target.node);
let data = std::fs::read(path)?;
// The whole name, extension and all: what becomes the title is
// `write_pdf_properties`' business, so it is the same rule on every path in.
let file_name = path.file_name().and_then(|s| s.to_str()).unwrap_or("Untitled");
import_blob_document(
blob_store,
doc_store,
artifact_store,
DocumentType::Pdf,
parent_id,
local_node,
&data,
progress,
|tx, doc_id, _| {
Ok(write_pdf_properties(doc_store, tx, doc_id, file_name, &data, local_node)?)
},
)
import_blob_document(target, DocumentType::Pdf, &data, |tx, doc_id, _| {
Ok(write_pdf_properties(doc_store, tx, doc_id, file_name, &data, local_node)?)
})
}
#[derive(Debug, thiserror::Error)]
@@ -576,16 +560,7 @@ mod tests {
let dir = TempDir::new().unwrap();
let path = dir.path().join(file_name);
std::fs::write(&path, bytes).unwrap();
import_pdf_file(
&store.blob_store,
&store.doc_store,
&store.artifact_store,
&path,
test_node(),
None,
None,
)
.unwrap()
import_pdf_file(&ImportTarget::new(store, test_node()), &path).unwrap()
}
/// A syntactically complete one-page PDF whose `/Info` dictionary is
+7 -21
View File
@@ -9,6 +9,7 @@ use crate::agents::blob_document::{
ImportError, import_blob_document, load_blob, primary_blob_ref,
};
use crate::content_fetch::{self, ContentFetchError};
use crate::documents::import::ImportTarget;
use crate::documents::{
BlobRef, Document, DocumentAvailability, DocumentID, DocumentType, PropertyKind,
document_availability_bulk,
@@ -17,7 +18,7 @@ use crate::jobs::runner::JobRunner;
use crate::node::NodePubkey;
use crate::stores::Store;
use crate::stores::artifact::{ArtifactStore, ArtifactStoreError};
use crate::stores::blob_store::{BlobStore, BlobStoreError, StoreProgress};
use crate::stores::blob_store::{BlobStore, BlobStoreError};
use crate::stores::document::{DocumentStore, DocumentStoreError};
#[derive(Debug, thiserror::Error)]
@@ -233,27 +234,12 @@ pub fn create_album(
doc_store.batch(|tx| add_titled(doc_store, tx, doc, title, local_node))
}
pub fn import_image_file(
blob_store: &BlobStore,
doc_store: &DocumentStore,
artifact_store: &ArtifactStore,
path: &Path,
local_node: NodePubkey,
parent_id: Option<&DocumentID>,
progress: Option<&dyn StoreProgress>,
) -> Result<DocumentID, ImportError> {
pub fn import_image_file(target: &ImportTarget, path: &Path) -> Result<DocumentID, ImportError> {
let (doc_store, local_node) = (&target.store.doc_store, target.node);
let data = std::fs::read(path)?;
let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("Untitled");
import_blob_document(
blob_store,
doc_store,
artifact_store,
DocumentType::Image,
parent_id,
local_node,
&data,
progress,
|tx, doc_id, _| Ok(write_image_properties(doc_store, tx, doc_id, stem, ext, local_node)?),
)
import_blob_document(target, DocumentType::Image, &data, |tx, doc_id, _| {
Ok(write_image_properties(doc_store, tx, doc_id, stem, ext, local_node)?)
})
}
+23 -58
View File
@@ -12,14 +12,14 @@ use std::collections::HashSet;
use std::path::Path;
use crate::agents::blob_document::{import_blob_document, load_blob, primary_blob_ref};
use crate::documents::import::ImportTarget;
use crate::documents::{
DocumentAvailability, DocumentID, DocumentType, PropertyKind, PropertyValue,
document_availability_bulk,
};
use crate::node::NodePubkey;
use crate::stores::Store;
use crate::stores::artifact::{ArtifactStore, ArtifactStoreError};
use crate::stores::blob_store::{BlobStore, BlobStoreError, StoreProgress};
use crate::stores::blob_store::{BlobStore, BlobStoreError};
use crate::stores::document::{DocumentStore, DocumentStoreError};
type Result<T> = std::result::Result<T, VideoError>;
@@ -89,15 +89,8 @@ pub fn probe_metadata(data: &[u8]) -> Result<VideoMetadata> {
})
}
pub fn import_video_file(
blob_store: &BlobStore,
doc_store: &DocumentStore,
artifact_store: &ArtifactStore,
path: &Path,
local_node: NodePubkey,
parent_id: Option<&DocumentID>,
progress: Option<&dyn StoreProgress>,
) -> Result<DocumentID> {
pub fn import_video_file(target: &ImportTarget, path: &Path) -> Result<DocumentID> {
let (doc_store, local_node) = (&target.store.doc_store, target.node);
let data = std::fs::read(path)?;
let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("").to_lowercase();
let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("Untitled").to_string();
@@ -111,34 +104,24 @@ pub fn import_video_file(
VideoMetadata::default()
});
import_blob_document(
blob_store,
doc_store,
artifact_store,
DocumentType::VideoClip,
parent_id,
local_node,
&data,
progress,
|tx, doc_id, _| {
let set = |kind, value: PropertyValue| {
doc_store.set_property(tx, doc_id, kind, value, local_node)
};
set(PropertyKind::Title, stem.into())?;
set(PropertyKind::FileType, ext.into())?;
for (kind, value) in [
(PropertyKind::VideoDurationSecs, metadata.duration_secs.map(PropertyValue::from)),
(PropertyKind::VideoWidth, metadata.width.map(PropertyValue::from)),
(PropertyKind::VideoHeight, metadata.height.map(PropertyValue::from)),
(PropertyKind::VideoCodec, metadata.codec.map(PropertyValue::from)),
] {
if let Some(value) = value {
set(kind, value)?;
}
import_blob_document(target, DocumentType::VideoClip, &data, |tx, doc_id, _| {
let set = |kind, value: PropertyValue| {
doc_store.set_property(tx, doc_id, kind, value, local_node)
};
set(PropertyKind::Title, stem.into())?;
set(PropertyKind::FileType, ext.into())?;
for (kind, value) in [
(PropertyKind::VideoDurationSecs, metadata.duration_secs.map(PropertyValue::from)),
(PropertyKind::VideoWidth, metadata.width.map(PropertyValue::from)),
(PropertyKind::VideoHeight, metadata.height.map(PropertyValue::from)),
(PropertyKind::VideoCodec, metadata.codec.map(PropertyValue::from)),
] {
if let Some(value) = value {
set(kind, value)?;
}
Ok(())
},
)
}
Ok(())
})
}
/// Load the raw (still-encoded) bytes of a video document's primary blob.
@@ -299,16 +282,7 @@ mod tests {
let path = dir.path().join("family trip.mp4");
std::fs::write(&path, b"not actually an mp4").unwrap();
let doc_id = import_video_file(
&store.blob_store,
&store.doc_store,
&store.artifact_store,
&path,
test_node(),
None,
None,
)
.unwrap();
let doc_id = import_video_file(&ImportTarget::new(&store, test_node()), &path).unwrap();
assert_eq!(get_title(&store.doc_store, &doc_id).as_deref(), Some("family trip"));
assert!(
@@ -324,16 +298,7 @@ mod tests {
let path = dir.path().join("clip.mp4");
std::fs::write(&path, b"not actually an mp4").unwrap();
let doc_id = import_video_file(
&store.blob_store,
&store.doc_store,
&store.artifact_store,
&path,
test_node(),
None,
None,
)
.unwrap();
let doc_id = import_video_file(&ImportTarget::new(&store, test_node()), &path).unwrap();
let nodes = build_video_nodes(&store).unwrap();
let node = nodes.iter().find(|n| n.id == doc_id).expect("imported clip is in the tree");
+131 -141
View File
@@ -6,9 +6,8 @@ use crate::copy::format_bytes;
use crate::documents::{Document, DocumentID, DocumentType, PropertyKind};
use crate::jobs::{JobProgress, ProgressReporter};
use crate::node::NodePubkey;
use crate::stores::artifact::ArtifactStore;
use crate::stores::blob_store::{BlobStore, StoreProgress};
use crate::stores::document::DocumentStore;
use crate::stores::Store;
use crate::stores::blob_store::StoreProgress;
#[derive(Clone, Copy)]
pub struct FileTypeFilter {
@@ -72,35 +71,80 @@ pub const COMIC_FILE_TYPES: FileTypeFilter = FileTypeFilter {
],
};
/// A supported document type: the filter that recognizes it (for file pickers)
/// paired with the function that imports one. The error is flattened to a
/// `String` so every type shares one signature and can live in a single table.
pub type ImportFn = fn(
&BlobStore,
&DocumentStore,
&ArtifactStore,
&Path,
NodePubkey,
Option<&DocumentID>,
Option<&dyn StoreProgress>,
) -> Result<DocumentID, String>;
/// Where an import lands: the store it writes, the node recorded as its author
/// (and as holding it), the collection it goes under, and the sink the blob
/// store reports bytes to as it seals the file.
#[derive(Clone, Copy)]
pub struct ImportTarget<'a> {
pub store: &'a Store,
pub node: NodePubkey,
pub parent: Option<&'a DocumentID>,
pub progress: Option<&'a dyn StoreProgress>,
}
impl<'a> ImportTarget<'a> {
/// The top level of `store`, with nothing watching the bytes.
pub fn new(store: &'a Store, node: NodePubkey) -> Self {
ImportTarget { store, node, parent: None, progress: None }
}
/// Record `doc_id`, just imported, as present on this node, so an import
/// counts toward this node's holdings whichever surface started it.
/// Best-effort: a failure is logged and the import stands, since the next
/// sync repairs a missing presence row.
pub(crate) fn mark_present(&self, doc_id: &DocumentID) {
let statuses = &self.store.node_doc_status_store;
if let Err(e) = statuses.batch(|tx| statuses.mark_present(tx, doc_id, &self.node)) {
log::warn!("Failed to mark document {doc_id} present: {e}");
}
}
}
/// How one supported type imports a path. The error is flattened to a
/// `String` so every type shares one signature and can live in a single table.
pub type ImportFn = fn(&ImportTarget, &Path) -> Result<DocumentID, String>;
/// A supported document type: the filter that recognizes it (for file pickers)
/// paired with the function that imports one.
pub struct SupportedFileType {
pub filter: FileTypeFilter,
pub import: ImportFn,
file: ImportFn,
/// Some for types that can also import an entire directory as a single
/// document (e.g. a folder of sequentially-named comic pages becoming one
/// Comic document). `None` means this type only makes sense for single files.
pub directory_import: Option<ImportFn>,
directory: Option<ImportFn>,
}
impl SupportedFileType {
/// Import the file at `path` as this type, marking it present on the
/// importing node.
pub fn import(&self, target: &ImportTarget, path: &Path) -> Result<DocumentID, String> {
(self.file)(target, path).inspect(|id| target.mark_present(id))
}
/// Whether this type can import a whole directory as one document.
pub fn imports_directories(&self) -> bool {
self.directory.is_some()
}
/// Import the directory `dir` as one document of this type, marking it
/// present on the importing node; `None` when the type has no directory
/// form.
pub fn import_directory(
&self,
target: &ImportTarget,
dir: &Path,
) -> Option<Result<DocumentID, String>> {
let import = self.directory?;
Some(import(target, dir).inspect(|id| target.mark_present(id)))
}
}
/// Adapts an agent's importer to the shared [`ImportFn`] signature,
/// flattening its typed error to a `String`.
macro_rules! import_fn {
($f:path) => {
|blobs, docs, artifacts, path, node, parent, progress| {
$f(blobs, docs, artifacts, path, node, parent, progress).map_err(|e| e.to_string())
}
|target, path| $f(target, path).map_err(|e| e.to_string())
};
}
@@ -113,91 +157,43 @@ macro_rules! import_fn {
pub const SUPPORTED_FILE_TYPES: &[SupportedFileType] = &[
SupportedFileType {
filter: PDF_FILE_TYPES,
import: import_fn!(pdf::import_pdf_file),
directory_import: None,
file: import_fn!(pdf::import_pdf_file),
directory: None,
},
SupportedFileType {
filter: IMAGE_FILE_TYPES,
import: import_fn!(pictures::import_image_file),
directory_import: None,
file: import_fn!(pictures::import_image_file),
directory: None,
},
SupportedFileType {
filter: MUSIC_FILE_TYPES,
import: import_fn!(music::import_mp3_file),
directory_import: None,
file: import_fn!(music::import_mp3_file),
directory: None,
},
SupportedFileType {
filter: VIDEO_FILE_TYPES,
import: import_fn!(video::import_video_file),
directory_import: None,
file: import_fn!(video::import_video_file),
directory: None,
},
SupportedFileType {
filter: COMIC_FILE_TYPES,
import: import_comic,
directory_import: Some(comics::import_comic_tree_single),
file: import_fn!(comics::import_comic_file),
directory: Some(comics::import_comic_tree_single),
},
];
fn import_comic(
blob_store: &BlobStore,
doc_store: &DocumentStore,
artifact_store: &ArtifactStore,
path: &Path,
node: NodePubkey,
parent: Option<&DocumentID>,
progress: Option<&dyn StoreProgress>,
) -> Result<DocumentID, String> {
// `cbr` is an optional feature (unrar's bundled C source isn't worth risking on
// every build, e.g. the Android NDK cross-compile — see its doc comment in
// Cargo.toml). When it's off, a `.cbr` falls through to the `.cbz` importer, which
// reports a clear-enough "not a valid .cbz archive" rather than silently mis-importing
// it; in practice every real consumer (cli-app, gui-app) enables the feature.
#[cfg(feature = "cbr")]
if path.extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("cbr")) {
return comics::import_cbr_file(
blob_store,
doc_store,
artifact_store,
path,
node,
parent,
progress,
)
.map_err(|e| e.to_string());
}
comics::import_cbz_file(blob_store, doc_store, artifact_store, path, node, parent, progress)
.map_err(|e| e.to_string())
}
/// Import `path` using the first supported type whose extension matches it.
/// `Ok(None)` means the file matched no known type and should be skipped.
/// Import `path` using the first supported type whose extension matches it,
/// marking it present on the importing node. `Ok(None)` means the file matched
/// no known type and should be skipped.
///
/// This is the one dispatch every caller should use, so the set of importable
/// types can never drift from the set offered in file pickers.
pub fn import_file(
blob_store: &BlobStore,
doc_store: &DocumentStore,
artifact_store: &ArtifactStore,
path: &Path,
node: NodePubkey,
parent: Option<&DocumentID>,
progress: Option<&dyn StoreProgress>,
) -> Result<Option<DocumentID>, String> {
for ty in SUPPORTED_FILE_TYPES {
if ty.filter.matches_path(path) {
return (ty.import)(
blob_store,
doc_store,
artifact_store,
path,
node,
parent,
progress,
)
.map(Some);
}
}
Ok(None)
pub fn import_file(target: &ImportTarget, path: &Path) -> Result<Option<DocumentID>, String> {
SUPPORTED_FILE_TYPES
.iter()
.find(|ty| ty.filter.matches_path(path))
.map(|ty| ty.import(target, path))
.transpose()
}
/// Whether any supported type recognizes `path`'s extension — i.e. whether
@@ -244,14 +240,12 @@ pub fn all_document_mime_types() -> Vec<&'static str> {
all_file_filters().flat_map(|f| f.mime_types.iter().copied()).collect()
}
/// Create a `Collection` document mirroring a host-system directory, used by
/// [`import_directory_tree`] when preserving structure.
pub fn create_collection_node(
doc_store: &DocumentStore,
dir: &Path,
parent: Option<&DocumentID>,
node: NodePubkey,
) -> Result<DocumentID, String> {
/// Create a `Collection` document under `target.parent` mirroring a
/// host-system directory, used by [`import_directory_tree`] when preserving
/// structure.
pub fn create_collection_node(target: &ImportTarget, dir: &Path) -> Result<DocumentID, String> {
let ImportTarget { store, node, parent, .. } = *target;
let doc_store = &store.doc_store;
let name = dir.file_name().and_then(|n| n.to_str()).unwrap_or("Collection").to_string();
let doc = Document::new(DocumentType::Collection, parent.cloned(), node);
let id = doc.id.clone();
@@ -275,19 +269,14 @@ pub struct ImportWalkStats {
}
/// Imports a single file, returning its new document (or `None` if the file
/// was skipped). Each GUI screen supplies its own — this is the only part of a
/// was skipped). Each caller supplies its own — this is the only part of a
/// directory walk that varies between them.
///
/// The third argument is the walk's byte sink, to hand to whatever stores the
/// file's contents: it belongs to the walk's own [`ImportProgress`], which the
/// closure has no other way to reach, and it is what lets one large file inside
/// a folder move the row before it lands.
pub type ImportOne<'a> = dyn FnMut(
&Path,
Option<&DocumentID>,
Option<&dyn StoreProgress>,
) -> Result<Option<DocumentID>, String>
+ 'a;
/// The target's `progress` is the walk's byte sink, to hand to whatever stores
/// the file's contents: it belongs to the walk's own [`ImportProgress`], which
/// the closure has no other way to reach, and it is what lets one large file
/// inside a folder move the row before it lands.
pub type ImportOne<'a> = dyn FnMut(&ImportTarget, &Path) -> Result<Option<DocumentID>, String> + 'a;
/// What an import expects to work through, counted before it starts: how many
/// files, and roughly how many bytes they hold.
@@ -591,7 +580,8 @@ pub fn count_tree(dir: &Path) -> ImportTotals {
/// aborts the whole import. When `preserve` is set, each subdirectory becomes a
/// [`DocumentType::Collection`] node (via [`create_collection_node`]) and its
/// files are parented beneath it; otherwise every file is imported flat under
/// `parent`.
/// `target.parent`. The walk hands `import_one` its own byte sink in place of
/// `target.progress`.
///
/// This is the one shared tree walk every "import a folder" flow should use —
/// GUI screens differ only in `import_one` and whether they offer `preserve` as
@@ -605,34 +595,30 @@ pub fn count_tree(dir: &Path) -> ImportTotals {
/// Whatever landed before the stop stays imported; a partial folder is the
/// honest outcome of canceling half way, and re-running picks up the rest.
pub fn import_directory_tree(
doc_store: &DocumentStore,
target: ImportTarget<'_>,
dir: &Path,
parent: Option<&DocumentID>,
preserve: bool,
node: NodePubkey,
import_one: &mut ImportOne<'_>,
job: Option<&dyn ProgressReporter>,
) -> ImportWalkStats {
// Don't pay for the pre-count when nobody is watching the result.
let total = job.map(|_| count_tree(dir));
let mut progress = ImportProgress::files(job, total);
let progress = ImportProgress::files(job, total);
let mut stats = ImportWalkStats::default();
import_tree(doc_store, dir, parent, preserve, node, import_one, &mut progress, &mut stats);
let target = ImportTarget { progress: Some(&progress), ..target };
import_tree(&target, &progress, dir, preserve, import_one, &mut stats);
stats
}
/// The recursive worker behind [`import_directory_tree`], carrying one
/// [`ImportProgress`] across every depth so the count is of the whole tree
/// rather than per directory.
#[allow(clippy::too_many_arguments)]
fn import_tree(
doc_store: &DocumentStore,
target: &ImportTarget,
progress: &ImportProgress<'_>,
dir: &Path,
parent: Option<&DocumentID>,
preserve: bool,
node: NodePubkey,
import_one: &mut ImportOne<'_>,
progress: &mut ImportProgress<'_>,
stats: &mut ImportWalkStats,
) {
let entries = match std::fs::read_dir(dir) {
@@ -655,18 +641,17 @@ fn import_tree(
};
if metadata.is_dir() {
let collection =
match preserve.then(|| create_collection_node(doc_store, &path, parent, node)) {
Some(Err(e)) => {
log::info!("Skipping {} (collection node failed: {e})", path.display());
continue;
}
created => created.and_then(Result::ok),
};
let next_parent = collection.as_ref().or(parent);
import_tree(doc_store, &path, next_parent, preserve, node, import_one, progress, stats);
let collection = match preserve.then(|| create_collection_node(target, &path)) {
Some(Err(e)) => {
log::info!("Skipping {} (collection node failed: {e})", path.display());
continue;
}
created => created.and_then(Result::ok),
};
let target = ImportTarget { parent: collection.as_ref().or(target.parent), ..*target };
import_tree(&target, progress, &path, preserve, import_one, stats);
} else if metadata.is_file() {
match import_one(&path, parent, Some(progress)) {
match import_one(target, &path) {
Ok(Some(_)) => stats.imported += 1,
Ok(None) => stats.skipped += 1,
Err(e) => {
@@ -683,7 +668,7 @@ fn import_tree(
#[cfg(test)]
mod tests {
use super::*;
use crate::test_support::{RecordingJob, TestStore, initialized_store, test_node};
use crate::test_support::{RecordingJob, TestStore, initialized_store, present_on, test_node};
use rstest::rstest;
use std::cell::Cell;
@@ -703,12 +688,10 @@ mod tests {
let job = RecordingJob::watching();
import_directory_tree(
&store.doc_store,
ImportTarget::new(&store, test_node()),
&dir,
None,
false,
test_node(),
&mut |_path, _parent, _progress| Ok(None),
&mut |_, _| Ok(None),
Some(&job),
);
@@ -803,12 +786,10 @@ mod tests {
let job = RecordingJob::canceling_after(1);
let visited = Cell::new(0usize);
import_directory_tree(
&store.doc_store,
ImportTarget::new(&store, test_node()),
&dir,
None,
false,
test_node(),
&mut |_path, _parent, _progress| {
&mut |_, _| {
visited.set(visited.get() + 1);
Ok(None)
},
@@ -844,6 +825,17 @@ mod tests {
assert_eq!(is_supported_path(Path::new(name)), expected);
}
/// Whichever surface imports a file, the importing node holds it.
#[rstest]
fn an_imported_file_is_present_on_the_importing_node(
#[from(initialized_store)] store: TestStore,
) {
let path = store.path.join("a.png");
std::fs::write(&path, b"not really a png").unwrap();
let id = import_file(&ImportTarget::new(&store, test_node()), &path).unwrap();
assert_eq!(id.map(|id| vec![id]), Some(present_on(&store, test_node())));
}
/// Nothing to report to, nothing to pre-count: the walk still runs.
#[rstest]
fn directory_walk_needs_no_job(#[from(initialized_store)] store: TestStore) {
@@ -853,12 +845,10 @@ mod tests {
let visited = Cell::new(0usize);
import_directory_tree(
&store.doc_store,
ImportTarget::new(&store, test_node()),
&dir,
None,
false,
test_node(),
&mut |_path, _parent, _progress| {
&mut |_, _| {
visited.set(visited.get() + 1);
Ok(None)
},
+7 -22
View File
@@ -298,6 +298,7 @@ mod tests {
use super::*;
use crate::agents::notebook::NotebookManager;
use crate::agents::{music, pdf};
use crate::documents::import::ImportTarget;
use crate::documents::{Document, Timestamp};
use crate::stores::node_content_status::ContentKey;
use crate::test_support::{
@@ -445,32 +446,16 @@ mod tests {
type Importer = fn(&TestStore, &Path, &DocumentID);
fn under<'a>(store: &'a TestStore, parent: &'a DocumentID) -> ImportTarget<'a> {
ImportTarget { parent: Some(parent), ..ImportTarget::new(store, test_node()) }
}
fn import_mp3(store: &TestStore, path: &Path, parent: &DocumentID) {
let s = store;
music::import_mp3_file(
&s.blob_store,
&s.doc_store,
&s.artifact_store,
path,
test_node(),
Some(parent),
None,
)
.unwrap();
music::import_mp3_file(&under(store, parent), path).unwrap();
}
fn import_pdf(store: &TestStore, path: &Path, parent: &DocumentID) {
let s = store;
pdf::import_pdf_file(
&s.blob_store,
&s.doc_store,
&s.artifact_store,
path,
test_node(),
Some(parent),
None,
)
.unwrap();
pdf::import_pdf_file(&under(store, parent), path).unwrap();
}
/// A blob passthrough is written byte for byte under the extension it was
+9 -12
View File
@@ -1,15 +1,14 @@
use thiserror::Error;
use crate::documents::import::{
FileTypeFilter, IMAGE_FILE_TYPES, MUSIC_FILE_TYPES, PDF_FILE_TYPES,
FileTypeFilter, IMAGE_FILE_TYPES, ImportTarget, MUSIC_FILE_TYPES, PDF_FILE_TYPES,
};
use crate::documents::{
Artifact, ArtifactValue, BlobRef, Document, DocumentID, DocumentType, PropertyKind,
};
use crate::node::NodePubkey;
use crate::stores::artifact::{ArtifactStore, ArtifactStoreError};
use crate::stores::blob_store::{BlobStore, BlobStoreError, StoreProgress};
use crate::stores::document::{DocumentStore, DocumentStoreError};
use crate::stores::artifact::ArtifactStoreError;
use crate::stores::blob_store::{BlobStoreError, StoreProgress};
use crate::stores::document::DocumentStoreError;
use crate::vault::DEFAULT_VAULT_ID;
#[derive(Debug, Error)]
@@ -80,13 +79,10 @@ fn http_error(url: &str) -> impl FnOnce(reqwest::Error) -> UrlImportError + '_ {
/// to matter.
pub async fn import_from_url(
url: &str,
blob_store: &BlobStore,
doc_store: &DocumentStore,
artifact_store: &ArtifactStore,
local_node: NodePubkey,
parent_id: Option<&DocumentID>,
progress: Option<&dyn StoreProgress>,
target: &ImportTarget<'_>,
) -> Result<UrlImportResult, UrlImportError> {
let ImportTarget { store, node: local_node, parent: parent_id, progress } = *target;
let (doc_store, artifact_store) = (&store.doc_store, &store.artifact_store);
let client = crate::http::build_async_client().map_err(http_error(url))?;
let response = client
@@ -114,7 +110,7 @@ pub async fn import_from_url(
let title = derive_title(url);
let bytes = download_reporting(response, url, progress).await?;
let stored = blob_store.store(&bytes, DEFAULT_VAULT_ID)?;
let stored = store.blob_store.store(&bytes, DEFAULT_VAULT_ID)?;
let doc = Document::new(doc_type, parent_id.cloned(), local_node);
let doc_id = doc.id.clone();
@@ -139,6 +135,7 @@ pub async fn import_from_url(
artifact_store.upsert_artifact(tx, &content)?;
Ok::<_, UrlImportError>(())
})?;
target.mark_present(&doc_id);
Ok(UrlImportResult { doc_id, doc_type, title })
}
+14 -27
View File
@@ -3,7 +3,8 @@ use std::sync::{Arc, Mutex};
use crate::copy::busy;
use crate::documents::DocumentID;
use crate::documents::import::{self, ImportCounts, ImportProgress, ImportTotals};
use crate::documents::import::{self, ImportCounts, ImportProgress, ImportTarget, ImportTotals};
use crate::documents::url_import;
use crate::jobs::runner::JobHandle;
use crate::jobs::{JobKind, JobOrigin, JobSubject, run_as_job_with_progress};
use crate::stores::Store;
@@ -118,16 +119,12 @@ impl ImportFfi {
url.clone(),
|reporter| {
let progress = ImportProgress::files(Some(reporter), Some(ImportTotals::file(0)));
let target = ImportTarget {
progress: Some(&progress),
..ImportTarget::new(&store, local_node)
};
let result = rt
.block_on(crate::documents::url_import::import_from_url(
&url,
&store.blob_store,
&store.doc_store,
&store.artifact_store,
local_node,
None,
Some(&progress),
))
.block_on(url_import::import_from_url(&url, &target))
.map(|r| r.doc_id)
.map_err(|e| SyncError::Internal { msg: e.to_string() });
progress.tick();
@@ -329,23 +326,13 @@ impl ImportBatch {
StagedFile::write(&store, &staged_name(file_name, mime_type), bytes).map_err(|e| {
SyncError::Internal { msg: format!("could not stage {file_name}: {e}") }
})?;
let doc_id = import::import_file(
&store.blob_store,
&store.doc_store,
&store.artifact_store,
&staged.path,
origin_node,
parent.as_ref(),
Some(self),
)
.map_err(|msg| SyncError::Internal { msg })?;
if let Some(doc_id) = &doc_id {
store
.node_doc_status_store
.batch(|tx| store.node_doc_status_store.mark_present(tx, doc_id, &origin_node))?;
}
Ok(doc_id)
let target = ImportTarget {
store: &store,
node: origin_node,
parent: parent.as_ref(),
progress: Some(self),
};
import::import_file(&target, &staged.path).map_err(|msg| SyncError::Internal { msg })
}
}
+7
View File
@@ -123,6 +123,13 @@ pub(crate) fn add_doc(
add_document(&store.doc_store, Document::new(doc_type, parent, test_node()))
}
/// The documents `node` is recorded as holding.
pub(crate) fn present_on(store: &Store, node: NodePubkey) -> Vec<DocumentID> {
let statuses = &store.node_doc_status_store;
let records = statuses.batch(|tx| statuses.list_documents_for_node(tx, &node)).unwrap();
records.into_iter().map(|r| r.document_id).collect()
}
/// A [`BlobRef`] for bytes that are nowhere on disk, told apart by `byte`.
pub(crate) fn missing_blob_ref(byte: u8, size: u64) -> BlobRef {
BlobRef::new(
+33 -94
View File
@@ -11,7 +11,8 @@ use synchronicity::agents::notebook::NotebookManager;
use synchronicity::copy;
use synchronicity::credentials::{self, ServiceId};
use synchronicity::documents::import::{
ImportProgress, ImportTotals, SupportedFileType, count_tree, create_collection_node,
ImportProgress, ImportTarget, ImportTotals, SupportedFileType, count_tree,
create_collection_node,
};
use synchronicity::documents::materialize::{MaterializeMode, materialize};
use synchronicity::documents::{
@@ -499,6 +500,8 @@ fn import_paths(
label,
|reporter| -> Result<ImportOutcome> {
let progress = ImportProgress::files(Some(reporter), Some(totals));
let target =
ImportTarget { progress: Some(&progress), ..ImportTarget::new(store, local_node) };
let mut outcome = ImportOutcome { events: Vec::new(), imported: 0, errors: 0 };
for path in paths {
@@ -525,7 +528,7 @@ fn import_paths(
if metadata.is_dir() { count_tree(path).bytes } else { metadata.len() };
if let Some(ty) = metadata.is_dir().then_some(forced_type).flatten() {
let Some(dir_import) = ty.directory_import else {
let Some(imported) = ty.import_directory(&target, path) else {
outcome.error(
path,
format!(
@@ -536,20 +539,11 @@ fn import_paths(
progress.tick_bytes(path_bytes);
continue;
};
match dir_import(
&store.blob_store,
&store.doc_store,
&store.artifact_store,
path,
local_node,
None,
Some(&progress),
) {
match imported {
Ok(doc_id) => {
mark_present(store, &doc_id, &local_node);
outcome.imported(path, doc_id, Some(ty.filter.name.to_string()));
outcome.imported(path, doc_id, Some(ty.filter.name.to_string()))
}
Err(e) => outcome.error(path, e.to_string()),
Err(e) => outcome.error(path, e),
}
// One directory imported as one document — one unit, unlike
// the walked-directory branch below which counts its files,
@@ -557,7 +551,7 @@ fn import_paths(
progress.tick_bytes(path_bytes);
} else if metadata.is_dir() {
let root_parent = if preserve_directory_structure {
match create_collection_node(&store.doc_store, path, None, local_node) {
match create_collection_node(&target, path) {
Ok(id) => {
outcome.events.push(ImportEvent::Collection {
path: path.display().to_string(),
@@ -574,36 +568,17 @@ fn import_paths(
None
};
import_directory_tree(
store,
path,
root_parent.as_ref(),
preserve_directory_structure,
local_node,
&ImportTarget { parent: root_parent.as_ref(), ..target },
&progress,
path,
preserve_directory_structure,
&mut outcome,
);
} else {
let result = if let Some(ty) = forced_type {
(ty.import)(
&store.blob_store,
&store.doc_store,
&store.artifact_store,
path,
local_node,
None,
Some(&progress),
)
.map_err(|e| anyhow::anyhow!(e))
ty.import(&target, path)
} else {
match import_file(
&store.blob_store,
&store.doc_store,
&store.artifact_store,
path,
local_node,
None,
Some(&progress),
) {
match import_file(&target, path) {
Ok(Some(doc_id)) => Ok(doc_id),
Ok(None) => {
let ext =
@@ -615,16 +590,13 @@ fn import_paths(
progress.tick_bytes(path_bytes);
continue;
}
Err(e) => Err(anyhow::anyhow!(e)),
Err(e) => Err(e),
}
};
match result {
Ok(doc_id) => {
mark_present(store, &doc_id, &local_node);
outcome.imported(path, doc_id, None);
}
Err(e) => outcome.error(path, e.to_string()),
Ok(doc_id) => outcome.imported(path, doc_id, None),
Err(e) => outcome.error(path, e),
}
progress.tick_bytes(path_bytes);
}
@@ -662,12 +634,10 @@ impl ImportOutcome {
/// `progress` is threaded through so the whole batch counts as one job — see
/// [`import_files`].
fn import_directory_tree(
store: &Store,
dir: &std::path::Path,
parent: Option<&DocumentID>,
preserve_structure: bool,
node: synchronicity::node::NodePubkey,
target: &ImportTarget,
progress: &ImportProgress<'_>,
dir: &std::path::Path,
preserve_structure: bool,
outcome: &mut ImportOutcome,
) {
use synchronicity::documents::import::import_file;
@@ -706,7 +676,7 @@ fn import_directory_tree(
if metadata.is_dir() {
let child_parent = if preserve_structure {
match create_collection_node(&store.doc_store, &path, parent, node) {
match create_collection_node(target, &path) {
Ok(id) => {
outcome.events.push(ImportEvent::Collection {
path: path.display().to_string(),
@@ -725,30 +695,17 @@ fn import_directory_tree(
} else {
None
};
let next_parent = if preserve_structure { child_parent.as_ref() } else { parent };
let parent = if preserve_structure { child_parent.as_ref() } else { target.parent };
import_directory_tree(
store,
&path,
next_parent,
preserve_structure,
node,
&ImportTarget { parent, ..*target },
progress,
&path,
preserve_structure,
outcome,
);
} else if metadata.is_file() {
match import_file(
&store.blob_store,
&store.doc_store,
&store.artifact_store,
&path,
node,
parent,
Some(progress),
) {
Ok(Some(doc_id)) => {
mark_present(store, &doc_id, &node);
outcome.imported(&path, doc_id, None);
}
match import_file(target, &path) {
Ok(Some(doc_id)) => outcome.imported(&path, doc_id, None),
Ok(None) => {
log::info!("Skipping unsupported file: {}", path.display());
}
@@ -776,7 +733,7 @@ fn expected_totals(
.map(|path| match std::fs::metadata(path) {
Ok(m) if m.is_dir() => {
let whole_dir_is_one_document =
forced_type.is_some_and(|ty| ty.directory_import.is_some());
forced_type.is_some_and(|ty| ty.imports_directories());
// A whole directory imported as one document is one unit, but
// still all of the tree's bytes.
let tree = count_tree(path);
@@ -812,21 +769,11 @@ async fn import_url(store: &Store, job_runner: &JobRunner, url: &str) -> Result<
|reporter| async move {
let progress =
ImportProgress::files(Some(reporter.as_ref()), Some(ImportTotals::file(0)));
let result = import_from_url(
url,
&store.blob_store,
&store.doc_store,
&store.artifact_store,
local_node,
None,
Some(&progress),
)
.await
.map_err(|e| anyhow::anyhow!("{e}"))?;
let target =
ImportTarget { progress: Some(&progress), ..ImportTarget::new(store, local_node) };
let result = import_from_url(url, &target).await.map_err(|e| anyhow::anyhow!("{e}"))?;
progress.tick();
mark_present(store, &result.doc_id, &local_node);
Ok(UrlImportOutcome { title: result.title, doc_id: result.doc_id })
},
)
@@ -950,15 +897,6 @@ fn local_node(store: &Store) -> Result<NodePubkey> {
.ok_or_else(|| anyhow::anyhow!("node not initialized — run `syn init` first"))
}
/// Record that this node now holds `doc_id`. Best-effort: the import itself
/// already succeeded, and a missed presence row is repaired by the next sync.
fn mark_present(store: &Store, doc_id: &DocumentID, node: &NodePubkey) {
let statuses = &store.node_doc_status_store;
if let Err(e) = statuses.batch(|tx| statuses.mark_present(tx, doc_id, node)) {
log::warn!("mark_present failed for {doc_id}: {e}");
}
}
/// The Notes agent — notebooks, notes and collections alike.
fn notes(store: &Store) -> Result<NotebookManager<'_>> {
Ok(NotebookManager::new(&store.doc_store, &store.artifact_store, local_node(store)?))
@@ -2005,7 +1943,8 @@ mod import_cancel_tests {
let progress = ImportProgress::files(reporter, None);
let mut outcome = ImportOutcome { events: Vec::new(), imported: 0, errors: 0 };
let node = NodePubkey([1u8; 32]);
import_directory_tree(&store, tree.path(), None, false, node, &progress, &mut outcome);
let target = ImportTarget::new(&store, node);
import_directory_tree(&target, &progress, tree.path(), false, &mut outcome);
outcome
}