1use 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
27pub(crate) const HEAD: usize = 8_192;
29
30#[derive(Clone, Debug, PartialEq, Eq)]
32pub struct AddedFile {
33 pub file: EntityId,
35 pub known: bool,
37 pub origin: Option<EntityId>,
41 pub content: Hash,
43 pub types: Vec<TypeName>,
45 pub kept: Kept,
47 pub unasked: bool,
50}
51
52#[derive(Clone, Debug, PartialEq, Eq)]
56pub struct Question {
57 pub folder: PathBuf,
59 pub size: u64,
61 pub rule: EntityId,
63}
64
65struct At {
68 metadata: fs::Metadata,
69 resolved: PathBuf,
70 found: Found,
71}
72
73struct Looked {
76 media_type: Option<String>,
77 recorded: media::Recorded,
78 types: Vec<TypeName>,
79 facts: Facts,
80}
81
82impl Library {
83 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 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 let passing = from.found.is_none() && self.in_temporary_folder(&resolved);
146 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 let mut needed: Vec<TypeName> = types.clone();
172 needed.push(ORIGIN);
173 self.install_standard(space, &needed, wall_millis, rng)?;
174
175 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 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 let origin = if known || passing {
224 self.name_source(space, &found, from, wall_millis, rng)?;
225 None
226 } else {
227 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 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 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 if !policies.asks_about(size) {
270 return Ok(None);
271 }
272 let At {
273 metadata,
274 resolved,
275 found,
276 } = at(path)?;
277 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 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 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 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 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 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 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 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 fn unchanged(
462 &self,
463 space: SpaceId,
464 found: &Found,
465 size: u64,
466 ) -> Result<Option<AddedFile>, NodeError> {
467 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 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 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 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 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 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 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 fn in_temporary_folder(&self, resolved: &Path) -> bool {
625 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 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 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 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 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 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 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 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 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 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
872type Values<'a> = &'a [(FieldName, Value)];
874
875type OwnedValues = Vec<(FieldName, Value)>;
877
878fn 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
907fn 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
930fn 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
950fn 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
978struct Found {
980 name: Option<String>,
982 path: String,
984 modified: Option<Edtf>,
986 created: Option<Edtf>,
988 source: Option<EntityId>,
990}
991
992impl Found {
993 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
1006fn 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
1014pub(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
1037pub(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
1044pub fn resolved_path(path: &Path) -> io::Result<PathBuf> {
1052 fs::canonicalize(path).map(plain)
1053}
1054
1055pub(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
1076pub(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 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(¬e, "Milk.\n").expect("writes");
1160 let added = library
1161 .add_file(personal, ¬e, now, &mut rng)
1162 .expect("adds");
1163 assert_eq!(added.types, [FILE]);
1164 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}