Skip to main content

nibkeep_node/library/
sources.rs

1//! Sources: where files came from, as the person names them when they import them, such as
2//! an old phone, a disc, a drive or Google Photos; each origin of a file found there names
3//! its source ([technical design: importers]).
4//!
5//! [technical design: importers]: ../../../../docs/Technical-design.md#912-importers-and-where-files-came-from
6
7use std::collections::BTreeSet;
8
9use nibkeep_base::{EntityId, SpaceId, StatementId};
10use nibkeep_crypto::rand_core::CryptoRng;
11use nibkeep_model::{FieldName, Name, Operation, Statement, Value, fields};
12use nibkeep_std::{DESCRIPTION, FOLDER, FROM_SOURCE, IN_FOLDER, SOURCE};
13use nibkeep_time::Edtf;
14
15use super::Library;
16use super::entities::NewValue;
17use super::policies::first_name;
18use crate::NodeError;
19
20/// A source of files, as a space records it.
21#[derive(Clone, Debug, PartialEq, Eq)]
22pub struct Source {
23	/// Its record.
24	pub id: EntityId,
25	/// Its name.
26	pub name: String,
27	/// What it is, if the person said.
28	pub description: Option<String>,
29	/// How many origins name it: files found there.
30	pub found: usize,
31}
32
33/// Where a file to add came from, beyond the folder it is read from: the source it was
34/// imported from, and its path and name there; where it was found, if it is read from a copy
35/// that is no original, as one unpacked from an archive; values that replace what it says
36/// of itself, as an archive's metadata; and the folders to put it in.
37#[derive(Clone, Debug, Default, PartialEq)]
38pub struct FileFrom {
39	/// The source it came from, by its record.
40	pub source: Option<EntityId>,
41	/// Its path within the source, its names joined by `/`.
42	pub source_path: Option<String>,
43	/// Its name in the source, where it differs from the name it is added under.
44	pub source_name: Option<String>,
45	/// Where it was found, if the file read is a copy of it that is no original: then the
46	/// file goes into the store, as nothing keeps it where it was found.
47	pub found: Option<FoundElsewhere>,
48	/// Values that replace what the file says of itself, where it says otherwise: on a file
49	/// the library holds already, only those that nobody changed since.
50	pub values: Vec<(FieldName, Value)>,
51	/// When it was taken, as where it was found says, such as a service that held it: it
52	/// replaces when the photo says it was taken, unless the photo's own time is the same
53	/// moment, written in its local time, which then stays, with its offset from UTC if it
54	/// had none ([`taken_of`]).
55	pub taken: Option<Edtf>,
56	/// Folders to put it in.
57	pub folders: Vec<EntityId>,
58}
59
60/// Where a file was found, when the file that is read is a copy of it, as one unpacked from
61/// an archive.
62#[derive(Clone, Debug, Default, PartialEq, Eq)]
63pub struct FoundElsewhere {
64	/// Where it was found: a path as people write it, such as the archive's path followed by
65	/// the path within it.
66	pub path: String,
67	/// Its name there.
68	pub name: Option<String>,
69	/// When it was last changed there, in milliseconds since 1970.
70	pub modified: Option<u64>,
71	/// When it was made there, in milliseconds since 1970, if known.
72	pub created: Option<u64>,
73}
74
75impl Library {
76	/// The sources of a space's files, ordered by name, each with how many files were found
77	/// there.
78	///
79	/// # Errors
80	///
81	/// Returns an error if the library has no such space, or it cannot be read.
82	pub fn sources(&self, space: SpaceId) -> Result<Vec<Source>, NodeError> {
83		let open = self.space(space)?;
84		let state = open.stored.log().state();
85		let mut sources = Vec::new();
86		let mut seen = BTreeSet::new();
87		for entity in open
88			.stored
89			.find(&fields::TYPE, &Value::Text(SOURCE.to_string()))?
90		{
91			let entity = state.canonical(entity)?;
92			if !seen.insert(entity) || state.is_deleted(entity)? {
93				continue;
94			}
95			let found = open
96				.stored
97				.find(&FROM_SOURCE, &Value::Reference(entity))?
98				.into_iter()
99				.filter(|origin| !state.is_deleted(*origin).unwrap_or(true))
100				.count();
101			sources.push(Source {
102				id: entity,
103				name: first_name(state, entity)?.unwrap_or_default(),
104				description: state
105					.current(entity, &DESCRIPTION)?
106					.first()
107					.and_then(|statement| statement.value.as_text().map(str::to_owned)),
108				found,
109			});
110		}
111		sources.sort_by_key(|source| (source.name.to_lowercase(), source.id));
112		Ok(sources)
113	}
114
115	/// The folder of a space named `name` in the folder `parent`, or in none, made if the
116	/// space has none, with `description` if it is made or has none, and whether it was made.
117	/// An importer puts albums in folders so.
118	///
119	/// # Errors
120	///
121	/// Returns [`NodeError::EmptyName`] for an empty name, and an error if the space cannot be
122	/// read or written.
123	pub fn folder_named(
124		&mut self,
125		space: SpaceId,
126		(name, parent): (&str, Option<EntityId>),
127		description: Option<&str>,
128		wall_millis: u64,
129		rng: &mut impl CryptoRng,
130	) -> Result<(EntityId, bool), NodeError> {
131		let name = name.trim();
132		if name.is_empty() {
133			return Err(NodeError::EmptyName);
134		}
135		let description = description.map(str::trim).filter(|text| !text.is_empty());
136		self.install_standard(space, &[FOLDER], wall_millis, rng)?;
137		let open = self.space(space)?;
138		let state = open.stored.log().state();
139		for entity in open
140			.stored
141			.find(&fields::TYPE, &Value::Text(FOLDER.to_string()))?
142		{
143			let entity = state.canonical(entity)?;
144			if state.is_deleted(entity)?
145				|| first_name(state, entity)?.is_none_or(|known| known != name)
146			{
147				continue;
148			}
149			let parents: Vec<EntityId> = state
150				.current(entity, &IN_FOLDER)?
151				.iter()
152				.filter_map(|statement| statement.value.as_reference())
153				.collect();
154			let same = match parent {
155				Some(parent) => parents.contains(&parent),
156				None => parents.is_empty(),
157			};
158			if !same {
159				continue;
160			}
161			// One that has no description gets this one.
162			if let Some(description) = description
163				&& state.current(entity, &DESCRIPTION)?.is_empty()
164			{
165				let operations = vec![Operation::assert(Statement::new(
166					StatementId::random(rng),
167					entity,
168					DESCRIPTION,
169					Value::Text(description.to_owned()),
170				))];
171				self.commit(space, operations, wall_millis, rng)?;
172			}
173			return Ok((entity, false));
174		}
175		let mut values = vec![NewValue::new(fields::NAME, Value::Name(Name::new(name)))];
176		if let Some(parent) = parent {
177			values.push(NewValue::new(IN_FOLDER, Value::Reference(parent)));
178		}
179		if let Some(description) = description {
180			values.push(NewValue::new(
181				DESCRIPTION,
182				Value::Text(description.to_owned()),
183			));
184		}
185		let (folder, operations) = self.new_entity(space, &[FOLDER], values, rng)?;
186		self.commit(space, operations, wall_millis, rng)?;
187		Ok((folder, true))
188	}
189
190	/// A folder on the library's disk for files that an importer unpacks before it adds
191	/// them, as from an archive, emptied of what an import cut short left: on the same disk,
192	/// so that a large file does not fill a smaller one, such as a temporary file system in
193	/// memory.
194	///
195	/// # Errors
196	///
197	/// Returns an error if the folder cannot be made.
198	pub fn scratch_folder(&self) -> Result<std::path::PathBuf, NodeError> {
199		let folder = self.directory.join("import");
200		if folder.exists() {
201			let _ = std::fs::remove_dir_all(&folder);
202		}
203		std::fs::create_dir_all(&folder).map_err(NodeError::file(&folder))?;
204		Ok(folder)
205	}
206
207	/// The source of a space named `name`, made if the space has none of that name, whatever
208	/// its case.
209	///
210	/// # Errors
211	///
212	/// Returns [`NodeError::EmptyName`] for an empty name, and an error if the space cannot be
213	/// read or written.
214	pub fn source_named(
215		&mut self,
216		space: SpaceId,
217		name: &str,
218		wall_millis: u64,
219		rng: &mut impl CryptoRng,
220	) -> Result<EntityId, NodeError> {
221		let name = name.trim();
222		if name.is_empty() {
223			return Err(NodeError::EmptyName);
224		}
225		if let Some(known) = self
226			.sources(space)?
227			.into_iter()
228			.find(|source| source.name.to_lowercase() == name.to_lowercase())
229		{
230			return Ok(known.id);
231		}
232		self.install_standard(space, &[SOURCE], wall_millis, rng)?;
233		let (source, operations) = self.new_entity(
234			space,
235			&[SOURCE],
236			vec![NewValue::new(fields::NAME, Value::Name(Name::new(name)))],
237			rng,
238		)?;
239		self.commit(space, operations, wall_millis, rng)?;
240		Ok(source)
241	}
242}
243
244/// When a photo was taken, of what it says itself, `own`, and what where it was found says,
245/// `given`: its own, if it is the same moment, to the second, as given, or the same moment in
246/// a time zone of whole quarter hours when it says no offset, which it then gets; else given,
247/// as when someone corrected the date where it was found.
248#[must_use]
249pub fn taken_of(own: Option<&Edtf>, given: &Edtf) -> Edtf {
250	let (Some(own), Some((given_local, given_offset))) = (own, given.local_seconds()) else {
251		return given.clone();
252	};
253	let Some((own_local, own_offset)) = own.local_seconds() else {
254		return given.clone();
255	};
256	let given_utc = given_local - i64::from(given_offset.unwrap_or(0)) * 60;
257	if let Some(offset) = own_offset {
258		let own_utc = own_local - i64::from(offset) * 60;
259		return if (own_utc - given_utc).abs() <= 1 {
260			own.clone()
261		} else {
262			given.clone()
263		};
264	}
265	// Local time ahead of UTC by the offset, within a second of a quarter hour.
266	let ahead = own_local - given_utc;
267	let quarters = (ahead + 450).div_euclid(900);
268	let off_by = (ahead - quarters * 900).abs();
269	if off_by <= 1 && (-12 * 4..=14 * 4).contains(&quarters) {
270		let minutes = i32::try_from(quarters * 15).unwrap_or(0);
271		own.with_offset(minutes).unwrap_or_else(|| own.clone())
272	} else {
273		given.clone()
274	}
275}
276
277#[cfg(test)]
278mod tests {
279	use super::*;
280
281	fn at(text: &str) -> Edtf {
282		text.parse().expect("a date")
283	}
284
285	#[test]
286	fn the_photos_own_time_stays_when_it_is_the_same_moment_and_a_corrected_one_wins() {
287		let given = at("2019-12-24T17:30:00Z");
288		// The same moment, written in local time with its offset.
289		assert_eq!(
290			taken_of(Some(&at("2019-12-24T18:30:00+01")), &given),
291			at("2019-12-24T18:30:00+01")
292		);
293		// The same moment, written without an offset: it gets the one the difference shows.
294		assert_eq!(
295			taken_of(Some(&at("2019-12-24T18:30:00")), &given),
296			at("2019-12-24T18:30:00+01")
297		);
298		assert_eq!(
299			taken_of(Some(&at("2019-12-24T23:00:00")), &given),
300			at("2019-12-24T23:00:00+05:30")
301		);
302		// A day apart: someone corrected the date where it was found.
303		assert_eq!(taken_of(Some(&at("2019-12-23T18:30:00+01")), &given), given);
304		assert_eq!(taken_of(Some(&at("2018-01-01T00:00:00")), &given), given);
305		// None of its own.
306		assert_eq!(taken_of(None, &given), given);
307	}
308}