Skip to main content

nibkeep_node/library/
files.rs

1//! Files: content that a person adds, stored once however often it is added, with each
2//! place it was found, and what a photo or a video says of itself (`docs/Design.md`,
3//! section 6.4).
4
5use std::fs::{self, File};
6use std::io::{self, Read};
7use std::panic::{AssertUnwindSafe, catch_unwind};
8use std::path::{Path, PathBuf};
9use std::time::{SystemTime, UNIX_EPOCH};
10
11use nibkeep_base::{EntityId, Hash, SpaceId};
12use nibkeep_crypto::rand_core::CryptoRng;
13use nibkeep_model::{FieldName, Name, Operation, TypeName, Value, fields};
14use nibkeep_std::{
15	CHECKOUT, CHECKOUT_OF, CONTENT, CREATED, FILE, FOLDER, FOUND_ON, FROM_SOURCE, IN_FOLDER,
16	IN_TREE, MEDIA_TYPE, MODIFIED, ORIGIN, ORIGIN_OF, PATH, PHOTO, SIZE, SOURCE_NAME, SOURCE_PATH,
17	TAKEN, VIDEO,
18};
19use nibkeep_time::{Day, Edtf};
20
21use super::entities::NewValue;
22use super::policies::{self, ChosenBy, Facts, Kept, NewRule, Place};
23use super::sources::{FileFrom, FoundElsewhere};
24use super::{Library, media};
25use crate::NodeError;
26
27/// How many of a file's first bytes tell its media type.
28pub(crate) const HEAD: usize = 8_192;
29
30/// What adding a file did.
31#[derive(Clone, Debug, PartialEq, Eq)]
32pub struct AddedFile {
33	/// The file: the entity of its content.
34	pub file: EntityId,
35	/// Whether the library held its content already, as this file.
36	pub known: bool,
37	/// The origin recorded for where it was found, or `None` if the library knew it found
38	/// there already, unchanged since, or it was in a temporary folder, whose paths are
39	/// not recorded.
40	pub origin: Option<EntityId>,
41	/// The hash of its content.
42	pub content: Hash,
43	/// Its types: a file, and a photo or a video if it says it is one.
44	pub types: Vec<TypeName>,
45	/// How this device holds it: in the store, or only where it was found.
46	pub kept: Kept,
47	/// Whether the rule that chose its policy asks whether a file as large can be got again,
48	/// and nobody answered for its folder, so that it went into the store.
49	pub unasked: bool,
50}
51
52/// A file large enough for the rule that would choose its policy to ask whether it can be
53/// got again, if it is lost: the answer counts for its folder, as [`Library::answer`] takes
54/// it.
55#[derive(Clone, Debug, PartialEq, Eq)]
56pub struct Question {
57	/// The folder the file is in, as the file system resolves it.
58	pub folder: PathBuf,
59	/// The file's size in bytes.
60	pub size: u64,
61	/// The rule that asks, before which the answer goes.
62	pub rule: EntityId,
63}
64
65/// Where a file is, as the file system says: what tells whether it changed since it was
66/// added there.
67struct At {
68	metadata: fs::Metadata,
69	resolved: PathBuf,
70	found: Found,
71}
72
73/// What a file says of itself before it is read in full: its media type from its first
74/// bytes, what a photo or a video says in its headers, and so what rules look at.
75struct Looked {
76	media_type: Option<String>,
77	recorded: media::Recorded,
78	types: Vec<TypeName>,
79	facts: Facts,
80}
81
82impl Library {
83	/// Adds the file at `path` to a space, found on this device. Its content is stored once:
84	/// a file whose content the space holds already, as a file, is that file, found again,
85	/// and a new origin records where, unless the space knows the file was found there,
86	/// unchanged since. A file that this device found at the same path, with the same size
87	/// and modification time, is taken to be unchanged and is not read again, as `rsync`
88	/// takes it. A new file is named as it was found, with its content's media type and
89	/// size, and is a photo or a video too if it says it is one, with when and where it was
90	/// taken, by which camera, and how large it is. The types it needs are added to the
91	/// space if it lacks them. Paths are kept as the file system resolves them, links and
92	/// `..` followed, so that one place has one path. A file in the system's temporary
93	/// folder, while the library is not there, goes into the store, and no origin records
94	/// where it was, as the folder is soon emptied.
95	///
96	/// Its storage policy, chosen before the file is read in full, says whether the device
97	/// keeps it in the store, or where it is, of which the space records its hash alone
98	/// ([technical design: storage policies]). The space gets the default policies if it never had them. A
99	/// file that the rule choosing for it would ask about, as [`Library::question_for`]
100	/// tells, goes into the store until [`Library::answer`] answers for its folder.
101	///
102	/// [technical design: storage policies]: ../../../../docs/Technical-design.md#93-storage-policies
103	///
104	/// # Errors
105	///
106	/// Returns [`NodeError::Unreadable`] if `path` is not a file that can be read,
107	/// [`NodeError::CheckedOut`] if it is the copy of a checkout on this device, and another
108	/// error if the library has no such space, the types cannot be added, or the content or
109	/// the changes cannot be saved.
110	pub fn add_file(
111		&mut self,
112		space: SpaceId,
113		path: &Path,
114		wall_millis: u64,
115		rng: &mut impl CryptoRng,
116	) -> Result<AddedFile, NodeError> {
117		self.add_file_from(space, path, &FileFrom::default(), wall_millis, rng)
118	}
119
120	/// Adds the file at `path` to a space, as [`Library::add_file`] does, from where `from`
121	/// says ([technical design: importers]): its origin names the source it was imported
122	/// from, with its path and name there; a file read from a copy that is no original, as
123	/// one unpacked from an archive, is found where `from` says, and goes into the store; the
124	/// values `from` gives replace what the file says of itself, but on a file the library
125	/// holds already, a value that someone changed since; and the file goes into the folders
126	/// it names. The same file found again from another source gets an origin of its own.
127	///
128	/// [technical design: importers]: ../../../../docs/Technical-design.md#912-importers-and-where-files-came-from
129	///
130	/// # Errors
131	///
132	/// As [`Library::add_file`].
133	pub fn add_file_from(
134		&mut self,
135		space: SpaceId,
136		path: &Path,
137		from: &FileFrom,
138		wall_millis: u64,
139		rng: &mut impl CryptoRng,
140	) -> Result<AddedFile, NodeError> {
141		self.install_policies(space, None, wall_millis, rng)?;
142		let (metadata, resolved, found) = self.found_where(space, path, from)?;
143		// A file in a temporary folder is soon gone: it goes into the store, and where it
144		// was is not recorded.
145		let passing = from.found.is_none() && self.in_temporary_folder(&resolved);
146		// A file found here before, unchanged, is not read again, unless its policy keeps it
147		// in the store now, and the device holds it only here.
148		let mut known = None;
149		if !passing && let Some(added) = self.unchanged(space, &found, metadata.len())? {
150			if added.kept == Kept::Store
151				|| self.policy_of(space, added.file)?.needs.kept == Kept::InPlace
152			{
153				self.name_source(space, &found, from, wall_millis, rng)?;
154				return Ok(added);
155			}
156			known = Some(added.file);
157		}
158		let Looked {
159			media_type,
160			recorded,
161			mut types,
162			facts,
163		} = self.look_inside(path, &resolved, &found, &metadata)?;
164		let (given, said) = given_and_said(&recorded, from);
165		let kind = kind_of(&recorded, &given, media_type.as_deref());
166		types.extend(kind.clone());
167		if !from.folders.is_empty() {
168			types.push(FOLDER);
169		}
170		// A space founded before these types, or one that dropped them, gets them now.
171		let mut needed: Vec<TypeName> = types.clone();
172		needed.push(ORIGIN);
173		self.install_standard(space, &needed, wall_millis, rng)?;
174
175		// A copy that is no original goes into the store: nothing keeps it where it was found.
176		let (kept, unasked) = if from.found.is_some() || passing {
177			(Kept::Store, false)
178		} else {
179			self.kept_for(space, known, &facts, metadata.len())?
180		};
181		let (content, size) =
182			self.read_content(space, (path, &resolved), kept, wall_millis, rng)?;
183		let existing = self.file_with(space, &content)?;
184		let mut stored = self.space(space)?.stored.holds_ordinary_blob(&content);
185		// The file it turns out to be may have a policy of its own, or be found elsewhere,
186		// so that its policy keeps it in the store after all.
187		if let Some(file) = existing
188			&& !stored
189			&& self.kept_by_policy(space, file, &found.path)? == Kept::Store
190		{
191			self.read_content(space, (path, &resolved), Kept::Store, wall_millis, rng)?;
192			stored = true;
193		}
194
195		let mut operations = Vec::new();
196		let file = if let Some(file) = existing {
197			file
198		} else {
199			let values = file_values(
200				&found,
201				(content, size, media_type.as_deref()),
202				(&said, &from.folders),
203			);
204			let file_types: Vec<TypeName> = types
205				.iter()
206				.filter(|kind| **kind != FOLDER)
207				.cloned()
208				.collect();
209			let (file, made) = self.new_entity(space, &file_types, new_values(values), rng)?;
210			operations.extend(made);
211			file
212		};
213		if existing.is_some() {
214			operations.extend(self.typed(space, file, kind, rng)?);
215			operations.extend(self.found_again(space, file, (&recorded.values, &given), rng)?);
216			operations.extend(self.putting_in_folders(space, file, &from.folders, rng)?);
217		}
218		let known = existing.is_some()
219			&& self
220				.known_origin(space, &found)?
221				.is_some_and(|(_, of)| of == file);
222		// A file found there before, or in a temporary folder, gets no new origin.
223		let origin = if known || passing {
224			self.name_source(space, &found, from, wall_millis, rng)?;
225			None
226		} else {
227			// What was found there stays what the origin says, whatever versions the file
228			// gets later.
229			let values = self.origin_values(file, (&found, from), (content, size));
230			let (origin, made) = self.new_entity(space, &[ORIGIN], new_values(values), rng)?;
231			operations.extend(made);
232			Some(origin)
233		};
234		if !operations.is_empty() {
235			self.commit(space, operations, wall_millis, rng)?;
236		}
237		// The file was read whole where it was found: the first check of the original there,
238		// which a copy that is no original is not.
239		if from.found.is_none() && !passing {
240			self.record_first_check(space, (found.path.clone(), content), wall_millis);
241		}
242		let types = match existing {
243			Some(file) => self.types_of(space, file)?,
244			None => types.into_iter().filter(|kind| *kind != FOLDER).collect(),
245		};
246		Ok(AddedFile {
247			file,
248			known: existing.is_some(),
249			origin,
250			content,
251			types,
252			kept: if stored { Kept::Store } else { Kept::InPlace },
253			unasked,
254		})
255	}
256
257	/// The question to ask before the file at `path` is added to a space, if the rule that
258	/// would choose its policy, as for a new file found there, asks about files as large:
259	/// whether it can be got again, if it is lost.
260	///
261	/// # Errors
262	///
263	/// Returns [`NodeError::Unreadable`] if `path` is not a file that can be read, and
264	/// another error if the library has no such space, or the space cannot be read.
265	pub fn question_for(&self, space: SpaceId, path: &Path) -> Result<Option<Question>, NodeError> {
266		let policies = self.read_policies(space)?;
267		let size = fs::metadata(path).map_or(0, |metadata| metadata.len());
268		// Most files are smaller than any rule asks about, and are not looked at.
269		if !policies.asks_about(size) {
270			return Ok(None);
271		}
272		let At {
273			metadata,
274			resolved,
275			found,
276		} = at(path)?;
277		// The answer changes nothing for a file found here before, unchanged, or a checkout.
278		if self.unchanged(space, &found, size)?.is_some() || self.is_checkout(space, &found.path)? {
279			return Ok(None);
280		}
281		let looked = self.look_inside(path, &resolved, &found, &metadata)?;
282		let choice = policies.choose(&[], &looked.facts);
283		Ok(match (choice.by, resolved.parent()) {
284			(ChosenBy::Rule(rule), Some(folder))
285				if choice.asks_above.is_some_and(|limit| size > limit) =>
286			{
287				Some(Question {
288					folder: plain(folder.to_owned()),
289					size,
290					rule,
291				})
292			}
293			_ => None,
294		})
295	}
296
297	/// Answers the question about a large file for its folder on this device: a rule that
298	/// chooses Replaceable for the files there if they can be got again, `again`, and
299	/// Standard if not, just before the rule that asked, so that it asks no more about them.
300	/// If the space no longer has that default policy, nothing is added, and such files go
301	/// into the store.
302	///
303	/// # Errors
304	///
305	/// Returns [`NodeError::Unreadable`] if the folder is not one, and another error if the
306	/// library has no such space, or the change cannot be saved.
307	pub fn answer(
308		&mut self,
309		space: SpaceId,
310		question: &Question,
311		again: bool,
312		wall_millis: u64,
313		rng: &mut impl CryptoRng,
314	) -> Result<(), NodeError> {
315		let policies = self.read_policies(space)?;
316		let policy = policies::answer_policy(space, again);
317		if !policies.has_policy(policy) {
318			return Ok(());
319		}
320		let place = if policies.has_rule(question.rule) {
321			Place::Before(question.rule)
322		} else {
323			Place::BeforeTheRest
324		};
325		let rule = NewRule {
326			folder: Some(question.folder.clone()),
327			..NewRule::new(policy)
328		};
329		self.add_rule(space, &rule, place, wall_millis, rng)?;
330		Ok(())
331	}
332
333	/// Where a file to add is kept, before it is read: as the policy of the file it is says,
334	/// if it was found here before, `known`, and otherwise as the rules choose for a new file
335	/// found here; and whether the rule that chose asks about a file as large, `size`, and
336	/// nobody answered, which sends it into the store.
337	fn kept_for(
338		&self,
339		space: SpaceId,
340		known: Option<EntityId>,
341		facts: &Facts,
342		size: u64,
343	) -> Result<(Kept, bool), NodeError> {
344		let choice = match known {
345			Some(file) => self.policy_of(space, file)?,
346			None => self.read_policies(space)?.choose(&[], facts),
347		};
348		let unasked =
349			choice.by != ChosenBy::Own && choice.asks_above.is_some_and(|limit| size > limit);
350		Ok((
351			if unasked {
352				Kept::Store
353			} else {
354				choice.needs.kept
355			},
356			unasked,
357		))
358	}
359
360	/// Where a file of a space is kept, as its policy says, once it is found at `place` on
361	/// this device too.
362	fn kept_by_policy(
363		&self,
364		space: SpaceId,
365		file: EntityId,
366		place: &str,
367	) -> Result<Kept, NodeError> {
368		let policies = self.read_policies(space)?;
369		let state = self.space(space)?.stored.log().state();
370		let mut facts = policies::facts_of(state, file)?;
371		facts.places.push((self.info.device, place.to_owned()));
372		let own = policies::own_choices(state, file)?;
373		Ok(policies.choose(&own, &facts).needs.kept)
374	}
375
376	/// Reads the file at `path`, resolved as `resolved`, in full, into the store of a space,
377	/// or only to hash it, if it is kept where it is, and returns the hash of its content and
378	/// its size.
379	fn read_content(
380		&mut self,
381		space: SpaceId,
382		(path, resolved): (&Path, &Path),
383		kept: Kept,
384		wall_millis: u64,
385		rng: &mut impl CryptoRng,
386	) -> Result<(Hash, u64), NodeError> {
387		let unreadable = |reason: String| NodeError::Unreadable {
388			path: path.display().to_string(),
389			reason,
390		};
391		let mut reading = Sniffing {
392			inner: File::open(resolved).map_err(|error| unreadable(error.to_string()))?,
393			size: 0,
394			failed: None,
395		};
396		let content = match kept {
397			Kept::Store => self.import_blob(space, &mut reading, wall_millis, rng),
398			Kept::InPlace => {
399				let mut hasher = nibkeep_base::Hasher::new();
400				io::copy(&mut reading, &mut hasher)
401					.map(|_| hasher.finalize())
402					.map_err(|error| unreadable(error.to_string()))
403			}
404		};
405		// An error of reading the file is the file's; any other is the library's.
406		match (content, reading.failed.take()) {
407			(Ok(content), _) => Ok((content, reading.size)),
408			(Err(_), Some(reason)) => Err(unreadable(reason)),
409			(Err(error), None) => Err(error),
410		}
411	}
412
413	/// Looks inside the file at `path`, resolved as `resolved` and found as `found`, before
414	/// reading it in full: its first bytes and its headers.
415	fn look_inside(
416		&self,
417		path: &Path,
418		resolved: &Path,
419		found: &Found,
420		metadata: &fs::Metadata,
421	) -> Result<Looked, NodeError> {
422		let mut head = Vec::with_capacity(HEAD);
423		File::open(resolved)
424			.and_then(|file| file.take(HEAD as u64).read_to_end(&mut head))
425			.map_err(|error| NodeError::Unreadable {
426				path: path.display().to_string(),
427				reason: error.to_string(),
428			})?;
429		let media_type = infer::get(&head).map(|kind| kind.mime_type().to_owned());
430		// What a photo or a video says is read from a file that may be anything; a reader
431		// that fails on it says nothing.
432		let recorded = catch_unwind(AssertUnwindSafe(|| media::read(resolved))).unwrap_or_default();
433		let mut types = vec![FILE];
434		types.extend(recorded.kind.clone());
435		let mut facts = Facts {
436			types: types.iter().cloned().collect(),
437			fields: [CONTENT, SIZE].into_iter().collect(),
438			media_type: media_type.clone(),
439			size: Some(metadata.len()),
440			places: vec![(self.info.device, found.path.clone())],
441		};
442		facts
443			.fields
444			.extend(recorded.values.iter().map(|(field, _)| field.clone()));
445		if found.name.is_some() {
446			facts.fields.insert(fields::NAME);
447		}
448		if media_type.is_some() {
449			facts.fields.insert(MEDIA_TYPE);
450		}
451		Ok(Looked {
452			media_type,
453			recorded,
454			types,
455			facts,
456		})
457	}
458
459	/// The file found before at the same place, if this device found it there with the
460	/// same size and modification time, which is taken to be unchanged, as it was then.
461	fn unchanged(
462		&self,
463		space: SpaceId,
464		found: &Found,
465		size: u64,
466	) -> Result<Option<AddedFile>, NodeError> {
467		// Without a modification time, only reading the file tells whether it changed.
468		if found.modified.is_none() {
469			return Ok(None);
470		}
471		let Some((origin, file)) = self.known_origin(space, found)? else {
472			return Ok(None);
473		};
474		let state = self.space(space)?.stored.log().state();
475		// What was found there, as the origin says.
476		let first = |field: &FieldName| -> Result<Option<Value>, NodeError> {
477			Ok(state
478				.current(origin, field)?
479				.first()
480				.map(|statement| statement.value.clone()))
481		};
482		let (Some(Value::Blob(content)), Some(Value::Integer(known_size))) =
483			(first(&CONTENT)?, first(&SIZE)?)
484		else {
485			return Ok(None);
486		};
487		if u64::try_from(known_size).ok() != Some(size) {
488			return Ok(None);
489		}
490		let stored = self.space(space)?.stored.holds_ordinary_blob(&content);
491		Ok(Some(AddedFile {
492			file,
493			known: true,
494			origin: None,
495			content,
496			types: self.types_of(space, file)?,
497			kept: if stored { Kept::Store } else { Kept::InPlace },
498			unasked: false,
499		}))
500	}
501
502	/// The file of a space whose content is this, if there is one: the first by ID, of
503	/// those that are not deleted; or else the file whose origin or checkout says it held
504	/// this content, as a version before its current one.
505	fn file_with(&self, space: SpaceId, content: &Hash) -> Result<Option<EntityId>, NodeError> {
506		let open = self.space(space)?;
507		let state = open.stored.log().state();
508		let holders = open.stored.find(&CONTENT, &Value::Blob(*content))?;
509		// A file of a tree is the file at its path, whatever its content (technical design:
510		// trees), never the file of content found elsewhere.
511		let is_file = |entity: EntityId| -> Result<bool, NodeError> {
512			Ok(!state.is_deleted(entity)?
513				&& state.types(entity)?.contains(&FILE)
514				&& state.current(entity, &IN_TREE)?.is_empty())
515		};
516		for &entity in &holders {
517			let entity = state.canonical(entity)?;
518			if is_file(entity)? {
519				return Ok(Some(entity));
520			}
521		}
522		for &holder in &holders {
523			let holder = state.canonical(holder)?;
524			let kinds = state.types(holder)?;
525			let of = if kinds.contains(&ORIGIN) {
526				ORIGIN_OF
527			} else if kinds.contains(&CHECKOUT) {
528				CHECKOUT_OF
529			} else {
530				continue;
531			};
532			if state.is_deleted(holder)? {
533				continue;
534			}
535			for file in found_at(state, (holder, &of))? {
536				if is_file(file)? {
537					return Ok(Some(file));
538				}
539			}
540		}
541		Ok(None)
542	}
543
544	/// The file that this device found where `found` says, as last changed at the same
545	/// moment, as an earlier import did: then adding it again records nothing, and an
546	/// importer need not unpack it to tell.
547	///
548	/// # Errors
549	///
550	/// Returns an error if the library has no such space, or it cannot be read.
551	pub fn found_before(
552		&self,
553		space: SpaceId,
554		found: &FoundElsewhere,
555	) -> Result<Option<EntityId>, NodeError> {
556		Ok(self
557			.known_origin(space, &Found::elsewhere(found))?
558			.map(|(_, file)| file))
559	}
560
561	/// An origin that says this device found a file at this path, as last changed at the
562	/// same moment, and the file, if neither is deleted.
563	fn known_origin(
564		&self,
565		space: SpaceId,
566		found: &Found,
567	) -> Result<Option<(EntityId, EntityId)>, NodeError> {
568		let open = self.space(space)?;
569		let state = open.stored.log().state();
570		let device = Value::Reference(self.info.device);
571		let modified = found.modified.clone().map(Value::Date);
572		for origin in open.stored.find(&PATH, &Value::Text(found.path.clone()))? {
573			let origin = state.canonical(origin)?;
574			let values = |field: &FieldName| -> Result<Vec<Value>, NodeError> {
575				Ok(state
576					.current(origin, field)?
577					.into_iter()
578					.map(|statement| statement.value.clone())
579					.collect())
580			};
581			if state.is_deleted(origin)?
582				|| !values(&FOUND_ON)?.contains(&device)
583				|| values(&MODIFIED)?.first() != modified.as_ref()
584			{
585				continue;
586			}
587			let Some(Value::Reference(file)) = values(&ORIGIN_OF)?.first().cloned() else {
588				continue;
589			};
590			let file = state.canonical(file)?;
591			if !state.is_deleted(file)? && state.types(file)?.contains(&FILE) {
592				return Ok(Some((origin, file)));
593			}
594		}
595		Ok(None)
596	}
597
598	/// Where the file at `path` is, as the file system resolves it, and where it was found,
599	/// as `from` says, or where it is, if it is no other's file, as a checkout or a tree's.
600	fn found_where(
601		&self,
602		space: SpaceId,
603		path: &Path,
604		from: &FileFrom,
605	) -> Result<(fs::Metadata, PathBuf, Found), NodeError> {
606		let At {
607			metadata,
608			resolved,
609			mut found,
610		} = at(path)?;
611		if let Some(elsewhere) = &from.found {
612			found = Found::elsewhere(elsewhere);
613		} else {
614			self.check_not_others(space, path, (&resolved, &found.path))?;
615		}
616		found.source = from.source;
617		Ok((metadata, resolved, found))
618	}
619
620	/// Whether a file at `resolved`, as the file system resolves it, is in the system's
621	/// temporary folder, while the library is not: such a folder is emptied, as an AI
622	/// agent's scratch folder is once its session ends, so a path there tells nothing
623	/// lasting. A library kept there is as passing as the files beside it.
624	fn in_temporary_folder(&self, resolved: &Path) -> bool {
625		// Resolved once for the process, as files are added by the thousand.
626		static TEMPORARY: std::sync::OnceLock<Option<PathBuf>> = std::sync::OnceLock::new();
627		let Some(temporary) = TEMPORARY.get_or_init(|| fs::canonicalize(std::env::temp_dir()).ok())
628		else {
629			return false;
630		};
631		resolved.starts_with(temporary)
632			&& !fs::canonicalize(&self.directory)
633				.is_ok_and(|library| library.starts_with(temporary))
634	}
635
636	/// What an origin records of where a file was found: the file, this device, the path,
637	/// the content and size found there, when it was changed and made there, and the source
638	/// it came from, with its path and name there.
639	fn origin_values(
640		&self,
641		file: EntityId,
642		(found, from): (&Found, &FileFrom),
643		(content, size): (Hash, u64),
644	) -> Vec<(FieldName, Value)> {
645		let mut values = vec![
646			(ORIGIN_OF, Value::Reference(file)),
647			(FOUND_ON, Value::Reference(self.info.device)),
648			(PATH, Value::Text(found.path.clone())),
649			(CONTENT, Value::Blob(content)),
650			(
651				SIZE,
652				Value::Integer(i64::try_from(size).unwrap_or(i64::MAX)),
653			),
654		];
655		values.extend(found.modified.clone().map(|at| (MODIFIED, Value::Date(at))));
656		values.extend(found.created.clone().map(|at| (CREATED, Value::Date(at))));
657		values.extend(
658			from.source
659				.map(|source| (FROM_SOURCE, Value::Reference(source))),
660		);
661		values.extend(
662			from.source_path
663				.clone()
664				.map(|path| (SOURCE_PATH, Value::Text(path))),
665		);
666		values.extend(
667			from.source_name
668				.clone()
669				.map(|name| (SOURCE_NAME, Value::Text(name))),
670		);
671		values
672	}
673
674	/// Names the source on the origin of a file found at the same place before, if it names
675	/// none: a place has one origin, and a source given later is added to it.
676	fn name_source(
677		&mut self,
678		space: SpaceId,
679		found: &Found,
680		from: &FileFrom,
681		wall_millis: u64,
682		rng: &mut impl CryptoRng,
683	) -> Result<(), NodeError> {
684		let Some(source) = from.source else {
685			return Ok(());
686		};
687		let Some((origin, _)) = self.known_origin(space, found)? else {
688			return Ok(());
689		};
690		let state = self.space(space)?.stored.log().state();
691		if !state.current(origin, &FROM_SOURCE)?.is_empty() {
692			return Ok(());
693		}
694		let mut operations = vec![Operation::assert(nibkeep_model::Statement::new(
695			nibkeep_base::StatementId::random(rng),
696			origin,
697			FROM_SOURCE,
698			Value::Reference(source),
699		))];
700		for (field, value) in [
701			(SOURCE_PATH, from.source_path.clone()),
702			(SOURCE_NAME, from.source_name.clone()),
703		] {
704			if let Some(value) = value {
705				operations.push(Operation::assert(nibkeep_model::Statement::new(
706					nibkeep_base::StatementId::random(rng),
707					origin,
708					field,
709					Value::Text(value),
710				)));
711			}
712		}
713		self.commit(space, operations, wall_millis, rng)
714	}
715
716	/// What gives a file the library holds already the type that where it was found again
717	/// says it has, as a photo, if it lacks it.
718	fn typed(
719		&self,
720		space: SpaceId,
721		file: EntityId,
722		kind: Option<TypeName>,
723		rng: &mut impl CryptoRng,
724	) -> Result<Vec<Operation>, NodeError> {
725		let Some(kind) = kind else {
726			return Ok(Vec::new());
727		};
728		let state = self.space(space)?.stored.log().state();
729		if state.types(file)?.contains(&kind) {
730			return Ok(Vec::new());
731		}
732		Ok(vec![Operation::assert(nibkeep_model::Statement::new(
733			nibkeep_base::StatementId::random(rng),
734			file,
735			fields::TYPE,
736			Value::Text(kind.to_string()),
737		))])
738	}
739
740	/// What a file the library holds already gets from where it was found again: the values
741	/// that `from` gives, where the file has none of that field, or the value the file said
742	/// of itself, `said`, which nobody changed since, unlike a value someone set.
743	fn found_again(
744		&self,
745		space: SpaceId,
746		file: EntityId,
747		(said, from): (Values<'_>, Values<'_>),
748		rng: &mut impl CryptoRng,
749	) -> Result<Vec<Operation>, NodeError> {
750		let state = self.space(space)?.stored.log().state();
751		let mut operations = Vec::new();
752		for (field, value) in from {
753			let current = state.current(file, field)?;
754			let as_said = said
755				.iter()
756				.find(|(known, _)| known == field)
757				.map(|(_, value)| value);
758			let replaceable = current.is_empty()
759				|| current
760					.iter()
761					.all(|statement| Some(&statement.value) == as_said);
762			if !replaceable || current.iter().any(|statement| statement.value == *value) {
763				continue;
764			}
765			operations.push(Operation::replace(
766				nibkeep_model::Statement::new(
767					nibkeep_base::StatementId::random(rng),
768					file,
769					field.clone(),
770					value.clone(),
771				),
772				current.iter().map(|statement| statement.id),
773			));
774		}
775		Ok(operations)
776	}
777
778	/// What puts a file into folders that it is not in yet.
779	fn putting_in_folders(
780		&self,
781		space: SpaceId,
782		file: EntityId,
783		folders: &[EntityId],
784		rng: &mut impl CryptoRng,
785	) -> Result<Vec<Operation>, NodeError> {
786		let state = self.space(space)?.stored.log().state();
787		let current = state.current(file, &IN_FOLDER)?;
788		let mut operations = Vec::new();
789		for folder in folders {
790			if current
791				.iter()
792				.any(|statement| statement.value == Value::Reference(*folder))
793			{
794				continue;
795			}
796			operations.push(Operation::assert(nibkeep_model::Statement::new(
797				nibkeep_base::StatementId::random(rng),
798				file,
799				IN_FOLDER,
800				Value::Reference(*folder),
801			)));
802		}
803		Ok(operations)
804	}
805
806	/// The types of an entity of a space, ordered by name.
807	fn types_of(&self, space: SpaceId, entity: EntityId) -> Result<Vec<TypeName>, NodeError> {
808		let state = self.space(space)?.stored.log().state();
809		Ok(state.types(entity)?.into_iter().collect())
810	}
811
812	/// Refuses a file to add that is another's: a checkout's copy, which is the file it is a
813	/// copy of, whose edits checking in records; or a file in a tree's folder, whose commits
814	/// record it (technical design: trees). `resolved` is its path as the file system resolves it,
815	/// and `text` that path as text.
816	fn check_not_others(
817		&self,
818		space: SpaceId,
819		path: &Path,
820		(resolved, text): (&Path, &str),
821	) -> Result<(), NodeError> {
822		if self.is_checkout(space, text)? {
823			return Err(NodeError::CheckedOut(path.to_owned()));
824		}
825		if self.in_any_tree(resolved)? {
826			return Err(NodeError::InTree(path.to_owned()));
827		}
828		Ok(())
829	}
830
831	/// Adds to a space what the standard types named lack, such as logins in a space made
832	/// before them, in a change of its own: each as carefully as the space defines its fields
833	/// already, after checking that it can be added so. Nothing is added if the space lacks
834	/// nothing.
835	///
836	/// # Errors
837	///
838	/// Returns an error if the library has no such space, if a type cannot be added, such as
839	/// one whose field the space defines with another kind, or if the change cannot be saved.
840	pub fn install_standard(
841		&mut self,
842		space: SpaceId,
843		names: &[TypeName],
844		wall_millis: u64,
845		rng: &mut impl CryptoRng,
846	) -> Result<(), NodeError> {
847		let mut operations: Vec<Operation> = Vec::new();
848		{
849			let open = self.space(space)?;
850			let types = &open.types;
851			for definition in nibkeep_std::types()
852				.iter()
853				.filter(|definition| names.contains(definition.name()))
854			{
855				// As careful as the space's own definitions, which a person may have made
856				// more careful, so that what is added is only what the space lacks.
857				let definition = types.careful(definition);
858				let lacking = types.define_in(&definition, open.stored.log().state(), rng)?;
859				if !lacking.is_empty() {
860					types.check(&definition)?;
861					operations.extend(lacking);
862				}
863			}
864		}
865		if operations.is_empty() {
866			return Ok(());
867		}
868		self.commit(space, operations, wall_millis, rng)
869	}
870}
871
872/// Values of fields, as a file says them of itself or where it was found says them.
873type Values<'a> = &'a [(FieldName, Value)];
874
875/// Values of fields, owned.
876type OwnedValues = Vec<(FieldName, Value)>;
877
878/// The values of a new file: its name where it was found, its content, media type and size,
879/// what it says of itself with what where it was found gives in place of it, `said`, and the
880/// folders it is in.
881fn file_values(
882	found: &Found,
883	(content, size, media_type): (Hash, u64, Option<&str>),
884	(said, folders): (Values<'_>, &[EntityId]),
885) -> OwnedValues {
886	let mut values: OwnedValues = Vec::new();
887	if let Some(name) = &found.name {
888		values.push((fields::NAME, Value::Name(Name::new(name))));
889	}
890	values.push((CONTENT, Value::Blob(content)));
891	if let Some(media_type) = media_type {
892		values.push((MEDIA_TYPE, Value::Text(media_type.to_owned())));
893	}
894	values.push((
895		SIZE,
896		Value::Integer(i64::try_from(size).unwrap_or(i64::MAX)),
897	));
898	values.extend(said.iter().cloned());
899	values.extend(
900		folders
901			.iter()
902			.map(|folder| (IN_FOLDER, Value::Reference(*folder))),
903	);
904	values
905}
906
907/// What `from` gives of a file in place of what it says of itself, `recorded`, the time it
908/// was taken as [`super::sources::taken_of`] decides it; and what it says of itself with
909/// that in place.
910fn given_and_said(recorded: &media::Recorded, from: &FileFrom) -> (OwnedValues, OwnedValues) {
911	let mut given = from.values.clone();
912	if let Some(taken) = &from.taken {
913		let own = recorded
914			.values
915			.iter()
916			.find_map(|(field, value)| match value {
917				Value::Date(at) if *field == TAKEN => Some(at),
918				_ => None,
919			});
920		given.push((TAKEN, Value::Date(super::sources::taken_of(own, taken))));
921	}
922	let mut said = recorded.values.clone();
923	for (field, value) in &given {
924		said.retain(|(known, _)| known != field);
925		said.push((field.clone(), value.clone()));
926	}
927	(given, said)
928}
929
930/// The type of a picture that says nothing of itself, by its media type: a photo or a video
931/// all the same, if where it was found says when or where it was taken.
932fn kind_of(
933	recorded: &media::Recorded,
934	given: Values<'_>,
935	media_type: Option<&str>,
936) -> Option<TypeName> {
937	if recorded.kind.is_some() || given.is_empty() {
938		return None;
939	}
940	let media = media_type?;
941	if media.starts_with("image/") {
942		Some(PHOTO)
943	} else if media.starts_with("video/") {
944		Some(VIDEO)
945	} else {
946		None
947	}
948}
949
950/// Where the file at `path` is, as the file system resolves it, and when it last changed.
951fn at(path: &Path) -> Result<At, NodeError> {
952	let unreadable = |reason: String| NodeError::Unreadable {
953		path: path.display().to_string(),
954		reason,
955	};
956	let metadata = fs::metadata(path).map_err(|error| unreadable(error.to_string()))?;
957	if !metadata.is_file() {
958		return Err(unreadable("not a file".to_owned()));
959	}
960	let resolved = fs::canonicalize(path).map_err(|error| unreadable(error.to_string()))?;
961	let found = Found {
962		name: path
963			.file_name()
964			.map(|name| name.to_string_lossy().into_owned())
965			.filter(|name| !name.is_empty()),
966		path: plain(resolved.clone()).to_string_lossy().into_owned(),
967		modified: metadata.modified().ok().and_then(moment),
968		created: metadata.created().ok().and_then(moment),
969		source: None,
970	};
971	Ok(At {
972		metadata,
973		resolved,
974		found,
975	})
976}
977
978/// Where a file was found, on this device.
979struct Found {
980	/// Its name there, if it has one that is not empty.
981	name: Option<String>,
982	/// Its path there, as the file system resolves it.
983	path: String,
984	/// When it was last changed there.
985	modified: Option<Edtf>,
986	/// When it was made there, if the file system says.
987	created: Option<Edtf>,
988	/// The source it came from, if it was imported from one.
989	source: Option<EntityId>,
990}
991
992impl Found {
993	/// Where a file was found that is read from a copy of it, as `from` says.
994	fn elsewhere(elsewhere: &FoundElsewhere) -> Self {
995		let at = |millis: u64| UNIX_EPOCH.checked_add(std::time::Duration::from_millis(millis));
996		Self {
997			name: elsewhere.name.clone().filter(|name| !name.is_empty()),
998			path: elsewhere.path.clone(),
999			modified: elsewhere.modified.and_then(at).and_then(moment),
1000			created: elsewhere.created.and_then(at).and_then(moment),
1001			source: None,
1002		}
1003	}
1004}
1005
1006/// Values without languages or other forms.
1007fn new_values(values: Vec<(FieldName, Value)>) -> Vec<NewValue> {
1008	values
1009		.into_iter()
1010		.map(|(field, value)| NewValue::new(field, value))
1011		.collect()
1012}
1013
1014/// The files that an origin says were found where it says, or that a checkout is a copy of,
1015/// each once, as the entities they were merged into: those of its current `std.origin-of`
1016/// or `std.checkout-of` statements, `of`, which a search that matches where they are finds
1017/// in its place.
1018pub(crate) fn found_at<S: nibkeep_model::storage::Statements>(
1019	state: &nibkeep_model::State<S>,
1020	(record, of): (EntityId, &FieldName),
1021) -> Result<Vec<EntityId>, NodeError>
1022where
1023	NodeError: From<S::Error>,
1024{
1025	let mut files = Vec::new();
1026	for statement in state.current(record, of)? {
1027		if let Some(file) = statement.value.as_reference() {
1028			let file = state.canonical(file)?;
1029			if !files.contains(&file) {
1030				files.push(file);
1031			}
1032		}
1033	}
1034	Ok(files)
1035}
1036
1037/// A moment of the file system, in UTC, to the second, such as `2026-10-12T10:00:00Z`.
1038pub(crate) fn moment(at: SystemTime) -> Option<Edtf> {
1039	let millis = u64::try_from(at.duration_since(UNIX_EPOCH).ok()?.as_millis()).ok()?;
1040	let day = Day::from_unix_millis(millis, 0)?;
1041	Edtf::moment(day, Day::second_of_day(millis, 0), 0)
1042}
1043
1044/// Where `path` is, as the file system resolves it, written as people write it: the form in
1045/// which a space keeps the path where a file was found, and the folder of a rule.
1046///
1047/// # Errors
1048///
1049/// Returns the file system's error if `path` cannot be resolved, such as when it does not
1050/// exist.
1051pub fn resolved_path(path: &Path) -> io::Result<PathBuf> {
1052	fs::canonicalize(path).map(plain)
1053}
1054
1055/// A path as people write it. Windows resolves paths into their extended form, such as
1056/// `\\?\C:\Photos`, which its other programs do not take; elsewhere, and where a path is
1057/// not Unicode, so that it would not name the same file again, paths are as they are.
1058pub(crate) fn plain(path: PathBuf) -> PathBuf {
1059	#[cfg(windows)]
1060	{
1061		let Some(text) = path.to_str() else {
1062			return path;
1063		};
1064		if let Some(rest) = text.strip_prefix(r"\\?\UNC\") {
1065			return PathBuf::from(format!(r"\\{rest}"));
1066		}
1067		if let Some(rest) = text.strip_prefix(r"\\?\")
1068			&& rest.as_bytes().get(1) == Some(&b':')
1069		{
1070			return PathBuf::from(rest);
1071		}
1072	}
1073	path
1074}
1075
1076/// A reader that counts the bytes it reads, and remembers why reading failed, so that an
1077/// error of the file is told from one of the library.
1078pub(crate) struct Sniffing<R> {
1079	pub(crate) inner: R,
1080	pub(crate) size: u64,
1081	pub(crate) failed: Option<String>,
1082}
1083
1084impl<R: Read> Read for Sniffing<R> {
1085	fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
1086		let read = self.inner.read(buffer).inspect_err(|error| {
1087			self.failed = Some(error.to_string());
1088		})?;
1089		self.size += read as u64;
1090		Ok(read)
1091	}
1092}
1093
1094#[cfg(test)]
1095mod tests {
1096	use nibkeep_crypto::PassphraseParams;
1097	use nibkeep_keys::NewProtection;
1098	use nibkeep_model::schema::TYPE_DEFINITION;
1099	use nibkeep_testkit::{TestRng, millis_at};
1100
1101	use super::*;
1102	use crate::NewLibrary;
1103
1104	#[test]
1105	fn paths_are_resolved_as_people_write_them() {
1106		let resolved = resolved_path(Path::new(".")).expect("resolves");
1107		assert!(resolved.is_absolute(), "{}", resolved.display());
1108		assert!(
1109			!resolved.to_string_lossy().starts_with(r"\\?\"),
1110			"{}",
1111			resolved.display()
1112		);
1113		#[cfg(windows)]
1114		{
1115			assert_eq!(
1116				plain(PathBuf::from(r"\\?\C:\Photos")),
1117				PathBuf::from(r"C:\Photos")
1118			);
1119			assert_eq!(
1120				plain(PathBuf::from(r"\\?\UNC\server\share\Photos")),
1121				PathBuf::from(r"\\server\share\Photos")
1122			);
1123		}
1124	}
1125
1126	#[test]
1127	fn a_space_without_the_types_of_files_gets_them() {
1128		let directory = nibkeep_testkit::empty_directory(
1129			std::env::temp_dir(),
1130			&format!("nibkeep-node-file-types-{}", std::process::id()),
1131		);
1132		let mut rng = TestRng::new("file types installed");
1133		let now = millis_at("2026-10-12", 10, 0);
1134		let protection = NewProtection::Passphrase(
1135			"correct horse",
1136			PassphraseParams::new(64, 1, 1).expect("valid"),
1137		);
1138		let mut library = Library::create(
1139			&directory,
1140			&NewLibrary::new("Ada", "laptop", "nib"),
1141			&protection,
1142			now,
1143			&mut rng,
1144		)
1145		.expect("creates");
1146		let personal = library.personal_space();
1147		let definitions = |library: &Library| {
1148			let open = library.space(personal).expect("a space");
1149			open.stored
1150				.find(&fields::TYPE, &Value::Text(TYPE_DEFINITION.to_string()))
1151				.expect("finds")
1152				.len()
1153		};
1154		let before = definitions(&library);
1155		// As a space founded before them sees its types.
1156		let space = library.spaces.get_mut(&personal).expect("a space");
1157		space.types = super::super::code_types();
1158		let note = directory.join("note.txt");
1159		fs::write(&note, "Milk.\n").expect("writes");
1160		let added = library
1161			.add_file(personal, &note, now, &mut rng)
1162			.expect("adds");
1163		assert_eq!(added.types, [FILE]);
1164		// std.file and std.origin are defined again.
1165		assert_eq!(definitions(&library), before + 2);
1166		assert!(
1167			library
1168				.space(personal)
1169				.expect("a space")
1170				.types
1171				.get(&FILE)
1172				.is_some()
1173		);
1174		drop(library);
1175		let _ = fs::remove_dir_all(&directory);
1176	}
1177}