Skip to main content

nibkeep_node/library/
linked_copies.rs

1//! Copies and edits of photos, linked, never merged ([technical design: importers]): a photo
2//! resized or saved again, as Google Photos keeps one, is linked to the larger by
3//! `std.copy-of`, and an edit to its original by `std.edit-of`. Each stays a file of its own,
4//! with its own origins and content, and a person who wants one file merges them.
5//!
6//! A copy is told by its thumbnail: taken in the same second, of the same proportions, and
7//! with picture hashes at most [`MOST_PICTURE_BITS_APART`] bits apart. Files found in one
8//! folder are never copies of each other, as photos of a burst taken within a second are
9//! alike; the smaller, in pixels and else in bytes, is the copy of the larger.
10//!
11//! [technical design: importers]: ../../../../docs/Technical-design.md#912-importers-and-where-files-came-from
12
13use std::collections::BTreeSet;
14
15use nibkeep_base::{EntityId, Hash, SpaceId, StatementId};
16use nibkeep_crypto::rand_core::CryptoRng;
17use nibkeep_model::storage::Statements as _;
18use nibkeep_model::{FieldName, Operation, Statement, Value};
19use nibkeep_std::{
20	CONTENT, COPY_OF, EDIT_OF, FILE, FOUND_ON, FROM_SOURCE, HEIGHT, IN_TREE,
21	MOST_PICTURE_BITS_APART, ORIGIN, ORIGIN_OF, PATH, PICTURE_HASH, SIZE, SOURCE_PATH, TAKEN,
22	WIDTH,
23};
24use nibkeep_time::Edtf;
25
26use super::Library;
27use super::thumbnails::{blob_of, gone};
28use crate::NodeError;
29
30/// The offsets from UTC, in minutes, that places use or used since cameras were digital,
31/// from −12 to +14 hours: a copy's time may be written in any of them, or in UTC, where its
32/// original's has another or none. Two times are the same second in these alone.
33const OFFSETS: [i32; 43] = [
34	-720, -660, -600, -570, -540, -480, -420, -360, -300, -270, -240, -210, -180, -150, -120, -60,
35	0, 60, 120, 180, 210, 240, 270, 300, 330, 345, 360, 390, 420, 480, 510, 525, 540, 570, 600,
36	630, 660, 690, 720, 765, 780, 825, 840,
37];
38
39/// How far apart the proportions of a picture's and its copy's thumbnails may be, as a
40/// share: thumbnails of small pictures round their sides.
41const PROPORTIONS_APART: u64 = 50;
42
43/// A folder that a file was found in: in a source, by the folder of its path there, or on a
44/// device.
45#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
46enum Folder {
47	InSource(EntityId, String),
48	OnDevice(EntityId, String),
49}
50
51/// What tells whether a file is a copy of another: when it was taken, its thumbnail's
52/// proportions and picture hash, its size, and the folders it was found in.
53#[derive(Clone, Debug)]
54struct Likeness {
55	file: EntityId,
56	content: Hash,
57	/// When it was taken, as [`Edtf::local_seconds`] gives it.
58	taken: (i64, Option<i32>),
59	/// Its thumbnail's width and height.
60	proportions: (u32, u32),
61	picture_hash: u64,
62	/// Its pixels, as its width and height say, if it has both.
63	pixels: Option<u64>,
64	bytes: Option<u64>,
65	folders: BTreeSet<Folder>,
66}
67
68impl Likeness {
69	/// Whether `other` looks like a copy of this file, or this of it.
70	fn alike(&self, other: &Self) -> bool {
71		self.file != other.file
72			&& self.content != other.content
73			&& same_second(self.taken, other.taken)
74			&& same_proportions(self.proportions, other.proportions)
75			&& (self.picture_hash ^ other.picture_hash).count_ones() <= MOST_PICTURE_BITS_APART
76			&& self.folders.is_disjoint(&other.folders)
77	}
78
79	/// Whether this file is larger than `other`: by pixels, a file that says none being
80	/// smaller than one that says, then by bytes, then by ID, as some order must decide. One
81	/// order, so that copies never link round to themselves.
82	fn larger_than(&self, other: &Self) -> bool {
83		self.size() > other.size()
84	}
85
86	/// What [`Likeness::larger_than`] compares.
87	fn size(&self) -> (u64, u64, std::cmp::Reverse<EntityId>) {
88		(
89			self.pixels.unwrap_or(0),
90			self.bytes.unwrap_or(0),
91			std::cmp::Reverse(self.file),
92		)
93	}
94}
95
96impl Library {
97	/// Links the files of `contents` that look like copies of others, or others like copies
98	/// of them, each to the larger it looks most like, as [`Likeness`] tells, unless it is or
99	/// was a copy of one already, or an edit of it. Returns how many it linked.
100	pub(super) fn link_copies_of(
101		&mut self,
102		space: SpaceId,
103		contents: &[Hash],
104		wall_millis: u64,
105		rng: &mut impl CryptoRng,
106	) -> Result<usize, NodeError> {
107		let mut seen = BTreeSet::new();
108		let mut linked = 0;
109		for content in contents {
110			for file in self.files_holding(space, content)? {
111				let Some(this) = self.likeness(space, file)? else {
112					continue;
113				};
114				let alike = self.alike(space, &this)?;
115				if seen.insert(this.file)
116					&& self.link_to_original(space, (&this, &alike), wall_millis, rng)?
117				{
118					linked += 1;
119				}
120				// Each that looks like it, unless linked already, may be a copy of it, or of
121				// another that looks more like it.
122				for one in alike {
123					if !seen.insert(one.file) || self.ever_had(space, one.file, &COPY_OF)? {
124						continue;
125					}
126					let its = self.alike(space, &one)?;
127					if self.link_to_original(space, (&one, &its), wall_millis, rng)? {
128						linked += 1;
129					}
130				}
131			}
132		}
133		Ok(linked)
134	}
135
136	/// Links an edit of a file, such as a photo that Google Photos keeps cropped beside its
137	/// original, to the original, by `std.edit-of`, unless it is or was an edit already, or
138	/// has the same content, or either is no file of the space, as one gone or moved away.
139	/// Returns whether it linked it.
140	///
141	/// # Errors
142	///
143	/// Returns an error if the library has no such space, or the space cannot be read or
144	/// saved.
145	pub fn link_edit(
146		&mut self,
147		space: SpaceId,
148		(edit, original): (EntityId, EntityId),
149		wall_millis: u64,
150		rng: &mut impl CryptoRng,
151	) -> Result<bool, NodeError> {
152		let open = self.space(space)?;
153		let state = open.stored.log().state();
154		let (edit, original) = (state.canonical(edit)?, state.canonical(original)?);
155		for file in [edit, original] {
156			if gone(state, file)? || !state.types(file)?.contains(&FILE) {
157				return Ok(false);
158			}
159		}
160		if edit == original
161			|| blob_of(state, edit, &CONTENT)? == blob_of(state, original, &CONTENT)?
162			|| self.ever_had(space, edit, &EDIT_OF)?
163		{
164			return Ok(false);
165		}
166		self.link(space, (edit, &EDIT_OF, original), wall_millis, rng)?;
167		Ok(true)
168	}
169
170	/// Links `copy` to the larger file it looks most like, by the fewest bits apart, then the
171	/// largest, unless it is or was a copy already: a link that a person removed stays
172	/// removed.
173	fn link_to_original(
174		&mut self,
175		space: SpaceId,
176		(copy, alike): (&Likeness, &[Likeness]),
177		wall_millis: u64,
178		rng: &mut impl CryptoRng,
179	) -> Result<bool, NodeError> {
180		if self.ever_had(space, copy.file, &COPY_OF)? {
181			return Ok(false);
182		}
183		let mut best: Option<&Likeness> = None;
184		for original in alike {
185			if !original.larger_than(copy)
186				|| self.edits_of_each_other(space, copy.file, original.file)?
187			{
188				continue;
189			}
190			let apart = |one: &Likeness| (one.picture_hash ^ copy.picture_hash).count_ones();
191			let better = best.is_none_or(|best| {
192				apart(original) < apart(best)
193					|| (apart(original) == apart(best) && original.larger_than(best))
194			});
195			if better {
196				best = Some(original);
197			}
198		}
199		let Some(original) = best else {
200			return Ok(false);
201		};
202		self.link(
203			space,
204			(copy.file, &COPY_OF, original.file),
205			wall_millis,
206			rng,
207		)?;
208		Ok(true)
209	}
210
211	/// The files that look like copies of `this`, or it like a copy of them, found by when
212	/// they were taken, as written in any time zone.
213	fn alike(&self, space: SpaceId, this: &Likeness) -> Result<Vec<Likeness>, NodeError> {
214		let open = self.space(space)?;
215		let state = open.stored.log().state();
216		let mut files = BTreeSet::new();
217		for moment in written_as(this.taken) {
218			for file in open.stored.find(&TAKEN, &Value::Date(moment))? {
219				files.insert(state.canonical(file)?);
220			}
221		}
222		let mut alike = Vec::new();
223		for file in files {
224			if let Some(other) = self.likeness(space, file)?
225				&& this.alike(&other)
226			{
227				alike.push(other);
228			}
229		}
230		Ok(alike)
231	}
232
233	/// The likeness of a file: none if it is gone, a tree's, or lacks a time taken or a
234	/// thumbnail with a picture hash.
235	fn likeness(&self, space: SpaceId, file: EntityId) -> Result<Option<Likeness>, NodeError> {
236		let open = self.space(space)?;
237		let state = open.stored.log().state();
238		let file = state.canonical(file)?;
239		if gone(state, file)?
240			|| !state.types(file)?.contains(&FILE)
241			|| !state.current(file, &IN_TREE)?.is_empty()
242		{
243			return Ok(None);
244		}
245		let Some(content) = blob_of(state, file, &CONTENT)? else {
246			return Ok(None);
247		};
248		let first = |entity: EntityId, field: &FieldName| -> Result<Option<Value>, NodeError> {
249			Ok(state
250				.current(entity, field)?
251				.first()
252				.map(|statement| statement.value.clone()))
253		};
254		let integer = |entity: EntityId, field: &FieldName| -> Result<Option<i64>, NodeError> {
255			Ok(match first(entity, field)? {
256				Some(Value::Integer(integer)) => Some(integer),
257				_ => None,
258			})
259		};
260		let Some(taken) = (match first(file, &TAKEN)? {
261			Some(Value::Date(taken)) => taken.local_seconds(),
262			_ => None,
263		}) else {
264			return Ok(None);
265		};
266		let mut shown = None;
267		for thumbnail in self.thumbnails_of(space, &content)? {
268			if let (Some(size), Some(hash)) =
269				(thumbnail.size, integer(thumbnail.entity, &PICTURE_HASH)?)
270			{
271				shown = Some((size, u64::from_be_bytes(hash.to_be_bytes())));
272				break;
273			}
274		}
275		let Some((proportions, picture_hash)) = shown else {
276			return Ok(None);
277		};
278		let positive = |value: Option<i64>| {
279			value
280				.and_then(|value| u64::try_from(value).ok())
281				.filter(|value| *value > 0)
282		};
283		let pixels = positive(integer(file, &WIDTH)?)
284			.zip(positive(integer(file, &HEIGHT)?))
285			.map(|(width, height)| width.saturating_mul(height));
286		let bytes = positive(integer(file, &SIZE)?);
287		let mut folders = BTreeSet::new();
288		for origin in open.stored.find(&ORIGIN_OF, &Value::Reference(file))? {
289			let origin = state.canonical(origin)?;
290			if gone(state, origin)? || !state.types(origin)?.contains(&ORIGIN) {
291				continue;
292			}
293			let reference = |field: &FieldName| -> Result<Option<EntityId>, NodeError> {
294				Ok(match first(origin, field)? {
295					Some(Value::Reference(entity)) => Some(entity),
296					_ => None,
297				})
298			};
299			let text = |field: &FieldName| -> Result<Option<String>, NodeError> {
300				Ok(first(origin, field)?.and_then(|value| value.as_text().map(str::to_owned)))
301			};
302			if let (Some(source), Some(path)) = (reference(&FROM_SOURCE)?, text(&SOURCE_PATH)?) {
303				folders.insert(Folder::InSource(source, parent_of(&path).to_owned()));
304			}
305			if let (Some(device), Some(path)) = (reference(&FOUND_ON)?, text(&PATH)?) {
306				folders.insert(Folder::OnDevice(device, parent_of(&path).to_owned()));
307			}
308		}
309		Ok(Some(Likeness {
310			file,
311			content,
312			taken,
313			proportions,
314			picture_hash,
315			pixels,
316			bytes,
317			folders,
318		}))
319	}
320
321	/// The files of a space whose current content is `content`, but those gone.
322	fn files_holding(&self, space: SpaceId, content: &Hash) -> Result<Vec<EntityId>, NodeError> {
323		let open = self.space(space)?;
324		let state = open.stored.log().state();
325		let mut files = BTreeSet::new();
326		for file in open.stored.find(&CONTENT, &Value::Blob(*content))? {
327			let file = state.canonical(file)?;
328			if !gone(state, file)? && state.types(file)?.contains(&FILE) {
329				files.insert(file);
330			}
331		}
332		Ok(files.into_iter().collect())
333	}
334
335	/// Whether `entity` has, or had, a value of `field`, current or replaced.
336	fn ever_had(
337		&self,
338		space: SpaceId,
339		entity: EntityId,
340		field: &FieldName,
341	) -> Result<bool, NodeError> {
342		let state = self.space(space)?.stored.log().state();
343		for member in state.merged(entity)? {
344			let had = state
345				.storage()
346				.of_entity(member)?
347				.into_iter()
348				.any(|(name, ids)| name == *field && !ids.is_empty());
349			if had {
350				return Ok(true);
351			}
352		}
353		Ok(false)
354	}
355
356	/// Whether one of two files is an edit of the other.
357	fn edits_of_each_other(
358		&self,
359		space: SpaceId,
360		one: EntityId,
361		other: EntityId,
362	) -> Result<bool, NodeError> {
363		let state = self.space(space)?.stored.log().state();
364		for (edit, original) in [(one, other), (other, one)] {
365			for statement in state.current(edit, &EDIT_OF)? {
366				if let Value::Reference(linked) = statement.value
367					&& state.canonical(linked)? == original
368				{
369					return Ok(true);
370				}
371			}
372		}
373		Ok(false)
374	}
375
376	/// Records that `from` refers to `to` in `field`, in a change of its own, the space's file
377	/// type installed first in the version that has the field.
378	fn link(
379		&mut self,
380		space: SpaceId,
381		(from, field, to): (EntityId, &FieldName, EntityId),
382		wall_millis: u64,
383		rng: &mut impl CryptoRng,
384	) -> Result<(), NodeError> {
385		self.install_standard(space, &[FILE], wall_millis, rng)?;
386		let operations = vec![Operation::assert(Statement::new(
387			StatementId::random(rng),
388			from,
389			field.clone(),
390			Value::Reference(to),
391		))];
392		self.commit(space, operations, wall_millis, rng)
393	}
394}
395
396/// The folder of a path, with `/` or `\\` between folders: all of it but its last name.
397fn parent_of(path: &str) -> &str {
398	path.rfind(['/', '\\']).map_or("", |slash| &path[..slash])
399}
400
401/// Whether two times taken, as [`Edtf::local_seconds`] gives them, are the same second: the
402/// same moment if both have an offset from UTC, the same local time if neither has, and else
403/// the same moment in one of the [`OFFSETS`].
404fn same_second(one: (i64, Option<i32>), other: (i64, Option<i32>)) -> bool {
405	let utc = |(local, offset): (i64, i32)| local - i64::from(offset) * 60;
406	match (one, other) {
407		((one, Some(this)), (other, Some(that))) => utc((one, this)) == utc((other, that)),
408		((one, None), (other, None)) => one == other,
409		((local, None), (with, Some(offset))) | ((with, Some(offset)), (local, None)) => {
410			let ahead = local - utc((with, offset));
411			ahead % 60 == 0
412				&& i32::try_from(ahead / 60).is_ok_and(|minutes| OFFSETS.contains(&minutes))
413		}
414	}
415}
416
417/// Whether two thumbnails' widths and heights have the same proportions, within
418/// 1/[`PROPORTIONS_APART`].
419fn same_proportions((width, height): (u32, u32), (other_width, other_height): (u32, u32)) -> bool {
420	let one = u64::from(width) * u64::from(other_height);
421	let other = u64::from(other_width) * u64::from(height);
422	one.abs_diff(other) * PROPORTIONS_APART <= one.max(other)
423}
424
425/// The ways a copy may write the time `taken`, as [`Edtf::local_seconds`] gives it: the same
426/// moment in each offset, with it or without; or, for a time without an offset, the same local
427/// time with each offset, and the moment it is in each, in UTC.
428fn written_as((local, offset): (i64, Option<i32>)) -> Vec<Edtf> {
429	let mut written = Vec::new();
430	if let Some(offset) = offset {
431		let utc = local - i64::from(offset) * 60;
432		for other in OFFSETS {
433			let there = utc + i64::from(other) * 60;
434			written.extend(Edtf::from_local_seconds(there, Some(other)));
435			written.extend(Edtf::from_local_seconds(there, None));
436		}
437	} else {
438		written.extend(Edtf::from_local_seconds(local, None));
439		for other in OFFSETS {
440			written.extend(Edtf::from_local_seconds(local, Some(other)));
441			written.extend(Edtf::from_local_seconds(
442				local - i64::from(other) * 60,
443				Some(0),
444			));
445		}
446	}
447	written.sort_by_key(ToString::to_string);
448	written.dedup();
449	written
450}
451
452#[cfg(test)]
453mod tests {
454	use super::*;
455
456	#[test]
457	fn the_same_second_is_found_in_any_time_zone_and_another_is_not() {
458		let at = |text: &str| -> (i64, Option<i32>) {
459			text.parse::<Edtf>()
460				.expect("a date and time")
461				.local_seconds()
462				.expect("a date and time")
463		};
464		let local = at("2019-12-24T18:30:00");
465		for same in [
466			"2019-12-24T18:30:00+01",
467			"2019-12-24T17:30:00Z",
468			"2019-12-24T18:30:00",
469		] {
470			assert!(same_second(local, at(same)), "{same}");
471			assert!(same_second(at(same), local), "{same}");
472			assert!(
473				written_as(local).contains(&same.parse().expect("a date")),
474				"{same}"
475			);
476		}
477		assert!(same_second(
478			at("2019-12-24T18:30:00+01"),
479			at("2019-12-24T12:30:00-05")
480		));
481		assert!(
482			written_as(at("2019-12-24T18:30:00+01"))
483				.contains(&"2019-12-24T12:30:00-05".parse().expect("a date"))
484		);
485		for other in [
486			"2019-12-24T18:30:01",
487			"2019-12-24T18:30:01Z",
488			"2019-12-24T18:31:00+01",
489		] {
490			assert!(!same_second(local, at(other)), "{other}");
491		}
492		assert!(!same_second(
493			at("2019-12-24T18:30:00+01"),
494			at("2019-12-24T18:30:00Z")
495		));
496	}
497
498	#[test]
499	fn proportions_are_the_same_but_for_rounding() {
500		assert!(same_proportions((512, 384), (512, 383)));
501		assert!(same_proportions((512, 384), (133, 100)));
502		assert!(!same_proportions((512, 384), (384, 512)));
503		assert!(!same_proportions((512, 384), (512, 288)));
504	}
505}