Skip to main content

nibkeep_node/library/
thumbnails.rs

1//! Thumbnails: small pictures of photos and videos that every replica keeps, so that a
2//! device shows a picture without its original ([technical design: thumbnails]). The device
3//! that adds a file makes its thumbnail, if it reads the file's format: the program brings
4//! what reads pictures, a [`Thumbnailer`], and the engine records what it makes, as an entity
5//! of the type `std.thumbnail` with a sealed blob of its own. A thumbnail belongs to a
6//! content, not to a file.
7//!
8//! [technical design: thumbnails]: ../../../../docs/Technical-design.md#98-thumbnails
9
10use std::cmp::Reverse;
11use std::collections::{BTreeMap, BTreeSet};
12use std::fs::File;
13use std::io::Write;
14use std::panic::{AssertUnwindSafe, catch_unwind};
15use std::path::Path;
16use std::sync::mpsc;
17use std::sync::{Arc, Mutex};
18
19use nibkeep_base::{EntityId, Hash, SpaceId, StatementId};
20use nibkeep_crypto::rand_core::CryptoRng;
21use nibkeep_model::storage::Statements;
22use nibkeep_model::{FieldName, State, Value, fields};
23use nibkeep_std::{
24	CONTENT, FILE, HEIGHT, IN_TREE, MADE_WITH, MEDIA_TYPE, PICTURE_HASH, TAKEN, THUMBNAIL,
25	THUMBNAIL_OF, WIDTH,
26};
27use nibkeep_time::{Day, Start};
28
29use super::Library;
30use super::checkouts::{put_in_place, remove_leftover, temporary_for};
31use super::entities::NewValue;
32use crate::NodeError;
33
34/// The most bytes of a picture read to make its thumbnail: larger pictures get none.
35pub const MOST_PICTURE_BYTES: u64 = 256 * 1024 * 1024;
36
37/// The most bytes of pictures being made into thumbnails at once, but one picture. Decoding
38/// takes about ten times a picture's bytes, so this keeps large pictures on many cores
39/// within about a gigabyte: a dozen photos of 12 megapixels at once, or three of 50.
40const MOST_BYTES_IN_FLIGHT: u64 = 96 * 1024 * 1024;
41
42/// How long the thumbnailer may take over a picture before it is left to finish alone, and
43/// the pictures it has not made count as unreadable: a decoder that a crafted picture sends
44/// round for ever does not hold up the program.
45const STUCK: std::time::Duration = std::time::Duration::from_secs(60);
46
47/// What reads pictures and makes their thumbnails, which a program brings: `nib` and
48/// apps on a computer bring decoders in memory-safe Rust. An app on Android brings none:
49/// it makes thumbnails with the phone's own decoders and hands them over, through
50/// [`Library::record_thumbnails_made`]. It runs on several threads at once.
51pub trait Thumbnailer: Send + Sync {
52	/// How it makes thumbnails, as each records it, such as `nibkeep 1`: who makes them, and
53	/// the version of their way, which counts up when the way changes.
54	fn made_with(&self) -> &str;
55
56	/// Whether it reads pictures of this media type, as their first bytes tell it, such as
57	/// `image/jpeg`.
58	fn reads(&self, media_type: &str) -> bool;
59
60	/// The thumbnail of a picture, from its bytes, or `None` if it cannot read them: a JPEG
61	/// whose longer side is at most 512 pixels, upright, without metadata.
62	fn make(&self, picture: &[u8]) -> Option<Thumbnail>;
63}
64
65/// A thumbnail that a [`Thumbnailer`] made: a JPEG, its size in pixels, and the picture
66/// hash of what it shows, if the thumbnailer makes one.
67#[derive(Clone, PartialEq, Eq)]
68pub struct Thumbnail {
69	/// The JPEG's bytes.
70	pub jpeg: Vec<u8>,
71	/// Its width.
72	pub width: u32,
73	/// Its height.
74	pub height: u32,
75	/// The picture hash of what it shows, which copies of the picture share, resized or
76	/// saved again, but for at most [`nibkeep_std::MOST_PICTURE_BITS_APART`] bits, as a
77	/// difference hash of 64 bits does: by which the engine links copies of photos.
78	pub picture_hash: Option<u64>,
79}
80
81impl std::fmt::Debug for Thumbnail {
82	fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
83		formatter
84			.debug_struct("Thumbnail")
85			.field("jpeg", &format_args!("{} bytes", self.jpeg.len()))
86			.field("width", &self.width)
87			.field("height", &self.height)
88			.field(
89				"picture_hash",
90				&self.picture_hash.map(|hash| format!("{hash:016x}")),
91			)
92			.finish()
93	}
94}
95
96/// What making thumbnails did.
97#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
98pub struct ThumbnailsMade {
99	/// How many thumbnails it made and recorded.
100	pub made: usize,
101	/// How many pictures the thumbnailer could not read, as of a format it does not read
102	/// after all, or damaged.
103	pub unreadable: usize,
104	/// How many pictures this device does not hold, neither in the store nor where they were
105	/// found, unchanged, or that are larger than [`MOST_PICTURE_BYTES`].
106	pub not_here: usize,
107	/// How many files it linked as copies of others, by their thumbnails' picture hashes.
108	pub copies_linked: usize,
109	/// Whether an error of the library stopped linking copies, after the thumbnails were
110	/// recorded.
111	pub linking_failed: bool,
112}
113
114impl std::ops::AddAssign for ThumbnailsMade {
115	fn add_assign(&mut self, other: Self) {
116		self.made += other.made;
117		self.unreadable += other.unreadable;
118		self.not_here += other.not_here;
119		self.copies_linked += other.copies_linked;
120		self.linking_failed |= other.linking_failed;
121	}
122}
123
124/// A thumbnail of a content, as a device shows it.
125#[derive(Clone, Debug, PartialEq, Eq)]
126pub struct ThumbnailOf {
127	/// The thumbnail's entity.
128	pub entity: EntityId,
129	/// Its own content: the JPEG.
130	pub content: Hash,
131	/// Its width and height in pixels, as it records them.
132	pub size: Option<(u32, u32)>,
133	/// How it was made, such as `nibkeep 1`.
134	pub made_with: Option<String>,
135	/// Whether this replica holds its JPEG.
136	pub held: bool,
137}
138
139/// How many of a space's files are pictures or videos, as their media types say, and how
140/// many of those have a thumbnail.
141#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
142pub struct ThumbnailCounts {
143	/// The files whose current content is an image or a video, but those of trees.
144	pub pictures: usize,
145	/// How many of them have a thumbnail.
146	pub with: usize,
147}
148
149/// The pictures handed to the workers: each content, and its bytes.
150type Jobs = mpsc::SyncSender<(Hash, Vec<u8>)>;
151
152/// What the workers made: each content, the size of its picture, and its thumbnail, if
153/// the thumbnailer read it.
154type Results = mpsc::Receiver<(Hash, u64, Option<Thumbnail>)>;
155
156/// A file whose current content is a picture or a video.
157struct Picture {
158	content: Hash,
159	media_type: String,
160	/// When it was taken, else when its content was recorded, to the second, for the newest
161	/// to come first.
162	newest: (Day, u32),
163}
164
165impl Library {
166	/// Brings what reads pictures, so that [`Library::make_thumbnails`] makes thumbnails.
167	/// Without one, as in a program that adds no files, none are made.
168	pub fn make_thumbnails_with(&mut self, thumbnailer: Arc<dyn Thumbnailer>) {
169		self.thumbnailer = Some(thumbnailer);
170	}
171
172	/// Makes the thumbnails of these contents of files of a space, those that lack one, as
173	/// the device that adds a file does: each that is the current content of a file that is
174	/// not a tree's, of a media type that the thumbnailer reads, that this device holds, in
175	/// the store or where it was found, unchanged, and no larger than [`MOST_PICTURE_BYTES`].
176	/// Pictures are read here and made into thumbnails on the computer's other cores, and
177	/// each thumbnail is recorded as it comes: sealed as a blob, in a change of its own. A
178	/// picture that cannot be read gets none, and is counted, as are those still in hand when
179	/// the thumbnailer has made nothing for a minute, which it is left to finish alone. Nothing is made without a
180	/// thumbnailer, by an AI agent's replica, which seals nothing, or where files' content is
181	/// secret.
182	///
183	/// # Errors
184	///
185	/// Returns an error if the library has no such space, or it cannot be read, or a
186	/// thumbnail cannot be saved; those recorded before stay.
187	pub fn make_thumbnails(
188		&mut self,
189		space: SpaceId,
190		contents: &[Hash],
191		wall_millis: u64,
192		rng: &mut impl CryptoRng,
193	) -> Result<ThumbnailsMade, NodeError> {
194		let Some(thumbnailer) = self.thumbnailer.clone() else {
195			return Ok(ThumbnailsMade::default());
196		};
197		if self.is_ai_agent()? || self.space(space)?.stored.secret_fields().contains(&CONTENT) {
198			return Ok(ThumbnailsMade::default());
199		}
200		let mut wanted = Vec::new();
201		let mut seen = BTreeSet::new();
202		for content in contents {
203			if seen.insert(*content)
204				&& !self.has_thumbnail(space, content)?
205				&& self
206					.picture_type(space, content)?
207					.is_some_and(|media_type| thumbnailer.reads(&media_type))
208			{
209				wanted.push(*content);
210			}
211		}
212		if wanted.is_empty() {
213			return Ok(ThumbnailsMade::default());
214		}
215		self.install_standard(space, &[THUMBNAIL], wall_millis, rng)?;
216		let workers = std::thread::available_parallelism()
217			.map_or(1, |cores| cores.get().saturating_sub(1))
218			.clamp(1, wanted.len());
219		// Workers of their own, never waited for: one that a picture holds for ever is left
220		// behind, and the others end once no more pictures come.
221		let (to_workers, jobs): (Jobs, _) = mpsc::sync_channel(workers);
222		let jobs = Arc::new(Mutex::new(jobs));
223		let (to_main, results): (_, Results) = mpsc::channel();
224		for _ in 0..workers {
225			let jobs = Arc::clone(&jobs);
226			let to_main = to_main.clone();
227			let thumbnailer = Arc::clone(&thumbnailer);
228			std::thread::spawn(move || {
229				loop {
230					// A worker that another's panic left without its lock stops.
231					let Ok(job) = jobs.lock().map(|jobs| jobs.recv()) else {
232						return;
233					};
234					let Ok((content, picture)) = job else {
235						return;
236					};
237					// A decoder that fails on a picture made to break it makes nothing.
238					let made = catch_unwind(AssertUnwindSafe(|| thumbnailer.make(&picture)))
239						.ok()
240						.flatten();
241					if to_main.send((content, picture.len() as u64, made)).is_err() {
242						return;
243					}
244				}
245			});
246		}
247		drop(to_main);
248		let mut made = self.record_as_made(
249			space,
250			(&wanted, &*thumbnailer),
251			(&to_workers, &results, workers),
252			wall_millis,
253			rng,
254		)?;
255		// With their pictures' hashes, files are linked as copies of others; an error of
256		// that leaves the thumbnails made.
257		match self.link_copies_of(space, &wanted, wall_millis, rng) {
258			Ok(linked) => made.copies_linked = linked,
259			Err(_) => made.linking_failed = true,
260		}
261		Ok(made)
262	}
263
264	/// Records thumbnails that the program made itself, each of a content of a space, as a
265	/// phone's app does, which reads the files it adds with the phone's own decoders: each
266	/// of a content that lacks one and is the current content of a picture or a video that
267	/// is not a tree's, recorded as made with `made_with`, such as `android 1`. The others
268	/// are left out. Nothing is recorded by an AI agent's replica, or where files' content
269	/// is secret.
270	///
271	/// # Errors
272	///
273	/// Returns an error if the library has no such space, or it cannot be read, or a
274	/// thumbnail cannot be saved; those recorded before stay.
275	pub fn record_thumbnails_made(
276		&mut self,
277		space: SpaceId,
278		thumbnails: &[(Hash, Thumbnail)],
279		made_with: &str,
280		wall_millis: u64,
281		rng: &mut impl CryptoRng,
282	) -> Result<ThumbnailsMade, NodeError> {
283		let mut made = ThumbnailsMade::default();
284		if self.is_ai_agent()? || self.space(space)?.stored.secret_fields().contains(&CONTENT) {
285			return Ok(made);
286		}
287		let mut recorded = Vec::new();
288		for (content, thumbnail) in thumbnails {
289			if self.has_thumbnail(space, content)? || self.picture_type(space, content)?.is_none() {
290				continue;
291			}
292			if recorded.is_empty() {
293				self.install_standard(space, &[THUMBNAIL], wall_millis, rng)?;
294			}
295			made +=
296				self.record_thumbnail(space, *content, (thumbnail, made_with), wall_millis, rng)?;
297			recorded.push(*content);
298		}
299		match self.link_copies_of(space, &recorded, wall_millis, rng) {
300			Ok(linked) => made.copies_linked = linked,
301			Err(_) => made.linking_failed = true,
302		}
303		Ok(made)
304	}
305
306	/// Reads the pictures of `wanted` and hands them to the workers, keeping at most twice
307	/// as many in flight as there are workers, and no more bytes than
308	/// [`MOST_BYTES_IN_FLIGHT`] but one picture; and records each thumbnail as it comes.
309	fn record_as_made(
310		&mut self,
311		space: SpaceId,
312		(wanted, thumbnailer): (&[Hash], &dyn Thumbnailer),
313		(to_workers, results, workers): (&Jobs, &Results, usize),
314		wall_millis: u64,
315		rng: &mut impl CryptoRng,
316	) -> Result<ThumbnailsMade, NodeError> {
317		let mut made = ThumbnailsMade::default();
318		let mut next = wanted.iter();
319		let (mut in_flight, mut bytes) = (0_usize, 0_u64);
320		loop {
321			while in_flight < 2 * workers && (in_flight == 0 || bytes < MOST_BYTES_IN_FLIGHT) {
322				let Some(content) = next.next() else {
323					break;
324				};
325				match self.file_content(space, content, MOST_PICTURE_BYTES)? {
326					Some(picture) => {
327						bytes += picture.len() as u64;
328						// Workers stop only once a decoder broke them all: the rest stay
329						// unmade.
330						if to_workers.send((*content, picture)).is_err() {
331							made.unreadable += 1;
332							continue;
333						}
334						in_flight += 1;
335					}
336					None => made.not_here += 1,
337				}
338			}
339			if in_flight == 0 {
340				return Ok(made);
341			}
342			let Ok((content, size, thumbnail)) = results.recv_timeout(STUCK) else {
343				made.unreadable += in_flight;
344				return Ok(made);
345			};
346			in_flight -= 1;
347			bytes = bytes.saturating_sub(size);
348			match thumbnail {
349				Some(thumbnail) => {
350					let one = self.record_thumbnail(
351						space,
352						content,
353						(&thumbnail, thumbnailer.made_with()),
354						wall_millis,
355						rng,
356					)?;
357					made += one;
358				}
359				None => made.unreadable += 1,
360			}
361		}
362	}
363
364	/// Records a thumbnail of a content of a space: its JPEG sealed as a blob, and an
365	/// entity of the type `std.thumbnail`, in a change of its own. A JPEG that is no
366	/// picture of a sensible size is not recorded, and counts as unreadable.
367	fn record_thumbnail(
368		&mut self,
369		space: SpaceId,
370		of: Hash,
371		(thumbnail, made_with): (&Thumbnail, &str),
372		wall_millis: u64,
373		rng: &mut impl CryptoRng,
374	) -> Result<ThumbnailsMade, NodeError> {
375		let sensible = |side: u32| (1..=4_096).contains(&side);
376		if thumbnail.jpeg.is_empty() || !sensible(thumbnail.width) || !sensible(thumbnail.height) {
377			return Ok(ThumbnailsMade {
378				unreadable: 1,
379				..ThumbnailsMade::default()
380			});
381		}
382		let content = self.import_blob(space, thumbnail.jpeg.as_slice(), wall_millis, rng)?;
383		let mut values = vec![
384			NewValue::new(THUMBNAIL_OF, Value::Blob(of)),
385			NewValue::new(CONTENT, Value::Blob(content)),
386			NewValue::new(MEDIA_TYPE, Value::Text("image/jpeg".to_owned())),
387			NewValue::new(WIDTH, Value::Integer(i64::from(thumbnail.width))),
388			NewValue::new(HEIGHT, Value::Integer(i64::from(thumbnail.height))),
389			NewValue::new(MADE_WITH, Value::Text(made_with.to_owned())),
390		];
391		if let Some(hash) = thumbnail.picture_hash {
392			values.push(NewValue::new(
393				PICTURE_HASH,
394				Value::Integer(i64::from_be_bytes(hash.to_be_bytes())),
395			));
396		}
397		let (_, operations) = self.new_entity(space, &[THUMBNAIL], values, rng)?;
398		self.commit(space, operations, wall_millis, rng)?;
399		Ok(ThumbnailsMade {
400			made: 1,
401			..ThumbnailsMade::default()
402		})
403	}
404
405	/// Makes the thumbnails that the files of a space lack, whichever device added them, as
406	/// `nib file thumbnails` does: for files added before thumbnails were made, or of a
407	/// format that a newer thumbnailer reads. The newest go first, by when a photo was
408	/// taken, else when its content was recorded, in rounds of `round`, after each of which
409	/// `progress` hears what was made so far, of how many.
410	///
411	/// # Errors
412	///
413	/// As [`Library::make_thumbnails`].
414	pub fn make_missing_thumbnails(
415		&mut self,
416		space: SpaceId,
417		round: usize,
418		wall_millis: u64,
419		rng: &mut impl CryptoRng,
420		progress: &mut dyn FnMut(ThumbnailsMade, usize),
421	) -> Result<ThumbnailsMade, NodeError> {
422		let missing = self.missing_thumbnails(space)?;
423		let mut made = ThumbnailsMade::default();
424		for contents in missing.chunks(round.max(1)) {
425			made += self.make_thumbnails(space, contents, wall_millis, rng)?;
426			progress(made, missing.len());
427		}
428		Ok(made)
429	}
430
431	/// The contents of the files of a space that lack a thumbnail, and of a media type that
432	/// the thumbnailer reads, newest first, as [`Library::make_missing_thumbnails`] makes
433	/// them; none without a thumbnailer.
434	///
435	/// # Errors
436	///
437	/// Returns an error if the library has no such space, or it cannot be read.
438	pub fn missing_thumbnails(&self, space: SpaceId) -> Result<Vec<Hash>, NodeError> {
439		let Some(thumbnailer) = &self.thumbnailer else {
440			return Ok(Vec::new());
441		};
442		let with = self.contents_with_thumbnails(space)?;
443		let mut missing: Vec<(Reverse<(Day, u32)>, Hash)> = self
444			.pictures(space)?
445			.into_values()
446			.filter(|picture| {
447				!with.contains(&picture.content) && thumbnailer.reads(&picture.media_type)
448			})
449			.map(|picture| (Reverse(picture.newest), picture.content))
450			.collect();
451		missing.sort();
452		Ok(missing.into_iter().map(|(_, content)| content).collect())
453	}
454
455	/// The thumbnail that a file of a space shows, of its current content: of those made of
456	/// it, the one made the newest way, the first recorded among those, as every device
457	/// chooses alike; `None` if none was made, or the file has no content.
458	///
459	/// # Errors
460	///
461	/// Returns an error if the library has no such space, or it cannot be read.
462	pub fn thumbnail(
463		&self,
464		space: SpaceId,
465		file: EntityId,
466	) -> Result<Option<ThumbnailOf>, NodeError> {
467		let open = self.space(space)?;
468		let state = open.stored.log().state();
469		let file = state.canonical(file)?;
470		let Some(content) = blob_of(state, file, &CONTENT)? else {
471			return Ok(None);
472		};
473		Ok(self.thumbnails_of(space, &content)?.into_iter().next())
474	}
475
476	/// The thumbnails made of a content, in the order that every device chooses the one shown
477	/// by: the one made the newest way first, the first recorded among those, then by ID.
478	pub(super) fn thumbnails_of(
479		&self,
480		space: SpaceId,
481		content: &Hash,
482	) -> Result<Vec<ThumbnailOf>, NodeError> {
483		let open = self.space(space)?;
484		let state = open.stored.log().state();
485		let mut made = Vec::new();
486		for thumbnail in open.stored.find(&THUMBNAIL_OF, &Value::Blob(*content))? {
487			let thumbnail = state.canonical(thumbnail)?;
488			if gone(state, thumbnail)? || !state.types(thumbnail)?.contains(&THUMBNAIL) {
489				continue;
490			}
491			let Some(jpeg) = state
492				.current(thumbnail, &CONTENT)?
493				.into_iter()
494				.find_map(|ours| match ours.value {
495					Value::Blob(jpeg) => Some((jpeg, ours.id)),
496					_ => None,
497				})
498			else {
499				continue;
500			};
501			let recorded = state
502				.storage()
503				.get(jpeg.1)?
504				.map(|recorded| recorded.at.millis());
505			let made_with = state
506				.current(thumbnail, &MADE_WITH)?
507				.first()
508				.and_then(|statement| statement.value.as_text().map(str::to_owned));
509			let pixels = |field: &FieldName| -> Result<Option<u32>, NodeError> {
510				Ok(state
511					.current(thumbnail, field)?
512					.first()
513					.and_then(|statement| match statement.value {
514						Value::Integer(pixels) => u32::try_from(pixels).ok(),
515						_ => None,
516					}))
517			};
518			let size = pixels(&WIDTH)?.zip(pixels(&HEIGHT)?);
519			let way = made_with.as_deref().map_or(0, way_of);
520			made.push((
521				(Reverse(way), recorded, thumbnail),
522				ThumbnailOf {
523					entity: thumbnail,
524					content: jpeg.0,
525					size,
526					made_with,
527					held: open.stored.holds_ordinary_blob(&jpeg.0),
528				},
529			));
530		}
531		made.sort_by_key(|(key, _)| *key);
532		made.dedup_by_key(|(key, _)| key.2);
533		Ok(made.into_iter().map(|(_, thumbnail)| thumbnail).collect())
534	}
535
536	/// Purges, in each space where this replica may, the thumbnails that it made of contents
537	/// that have another thumbnail shown, as two devices that add one photo before they sync
538	/// both make one ([technical design: thumbnails]): each whole, but its marks, and its own
539	/// content unless something else holds that; once the one shown is held here, so that
540	/// this device shows a picture all along. The device that made a thumbnail purges it, as
541	/// a member may purge what they wrote; one that never syncs again leaves its own. Returns
542	/// how many it purged.
543	///
544	/// [technical design: thumbnails]: ../../../../docs/Technical-design.md#98-thumbnails
545	///
546	/// # Errors
547	///
548	/// Returns an error if a space cannot be read, or a purge cannot be saved.
549	pub fn purge_thumbnails_made_twice(
550		&mut self,
551		wall_millis: u64,
552		rng: &mut impl CryptoRng,
553	) -> Result<usize, NodeError> {
554		if self.is_ai_agent()? {
555			return Ok(0);
556		}
557		let own = self.replica.signing.verifying_key();
558		let mut purged = 0;
559		for space in self.spaces() {
560			if self.check_not_revoked(space).is_err() {
561				continue;
562			}
563			let mut made_twice = Vec::new();
564			let mut counted: BTreeMap<Hash, usize> = BTreeMap::new();
565			{
566				let open = self.space(space)?;
567				let state = open.stored.log().state();
568				for thumbnail in open
569					.stored
570					.find(&fields::TYPE, &Value::Text(THUMBNAIL.to_string()))?
571				{
572					let thumbnail = state.canonical(thumbnail)?;
573					if gone(state, thumbnail)? || blob_of(state, thumbnail, &CONTENT)?.is_none() {
574						continue;
575					}
576					if let Some(of) = blob_of(state, thumbnail, &THUMBNAIL_OF)? {
577						*counted.entry(of).or_default() += 1;
578					}
579				}
580			}
581			for (content, count) in counted {
582				if count < 2 {
583					continue;
584				}
585				let made = self.thumbnails_of(space, &content)?;
586				let Some((shown, others)) = made.split_first() else {
587					continue;
588				};
589				if !shown.held {
590					continue;
591				}
592				for other in others {
593					if self.wrote_only(space, other.entity, &own)? {
594						made_twice.push(other.entity);
595					}
596				}
597			}
598			if made_twice.is_empty() {
599				continue;
600			}
601			// One purge of them all in the space, which reads its values once.
602			let (statements, contents) = self.thumbnails_whole(space, &made_twice)?;
603			if statements.is_empty() {
604				continue;
605			}
606			let contents: Vec<Hash> = contents.into_iter().collect();
607			self.purge_statements(space, &statements, (&contents, false), wall_millis, rng)?;
608			purged += made_twice.len();
609		}
610		Ok(purged)
611	}
612
613	/// Whether every value that an entity of a space has held, current or past, came from
614	/// changes of this replica's own key.
615	fn wrote_only(
616		&self,
617		space: SpaceId,
618		entity: EntityId,
619		own: &nibkeep_crypto::VerifyingKey,
620	) -> Result<bool, NodeError> {
621		let open = self.space(space)?;
622		let log = open.stored.log();
623		for (_, ids) in log.state().storage().of_entity(entity)? {
624			for id in ids {
625				if log.author_of(id)?.is_none_or(|author| author != *own) {
626					return Ok(false);
627				}
628			}
629		}
630		Ok(true)
631	}
632
633	/// The statements of thumbnails that a purge of them whole takes, every value they have
634	/// held but their marks of a move or a merge, and their own contents, but those that
635	/// another value of the space holds.
636	fn thumbnails_whole(
637		&self,
638		space: SpaceId,
639		thumbnails: &[EntityId],
640	) -> Result<(Vec<StatementId>, BTreeSet<Hash>), NodeError> {
641		let open = self.space(space)?;
642		let secret_fields = open.stored.secret_fields();
643		let storage = open.stored.log().state().storage();
644		let mut statements = Vec::new();
645		let mut pictures = BTreeSet::new();
646		for thumbnail in thumbnails {
647			for (field, ids) in storage.of_entity(*thumbnail)? {
648				if super::behind::is_mark(&field) {
649					continue;
650				}
651				for id in ids {
652					statements.push(id);
653					if field == CONTENT
654						&& let Some(recorded) = storage.get(id)?
655						&& let Value::Blob(picture) = recorded.statement.value
656					{
657						pictures.insert(picture);
658					}
659				}
660			}
661		}
662		if !pictures.is_empty() {
663			let theirs: BTreeSet<StatementId> = statements.iter().copied().collect();
664			for entity in storage.described()? {
665				for (field, ids) in storage.of_entity(entity)? {
666					if secret_fields.contains(&field) {
667						continue;
668					}
669					for id in ids {
670						if !theirs.contains(&id)
671							&& let Some(recorded) = storage.get(id)?
672							&& let Value::Blob(held) = &recorded.statement.value
673						{
674							pictures.remove(held);
675						}
676					}
677				}
678			}
679		}
680		Ok((statements, pictures))
681	}
682
683	/// The JPEG of a thumbnail, from the copy this replica holds, or `None` if it holds none.
684	///
685	/// # Errors
686	///
687	/// Returns an error if the library has no such space, or it cannot be read.
688	pub fn thumbnail_jpeg(
689		&self,
690		space: SpaceId,
691		thumbnail: &ThumbnailOf,
692	) -> Result<Option<Vec<u8>>, NodeError> {
693		let open = self.space(space)?;
694		if !open.stored.holds_ordinary_blob(&thumbnail.content) {
695			return Ok(None);
696		}
697		self.file_content(space, &thumbnail.content, MOST_PICTURE_BYTES)
698	}
699
700	/// Writes the JPEG of a thumbnail into a new file at `path`, for scripts and tests. It
701	/// replaces nothing: the JPEG is written beside `path` first, synced, and then put in
702	/// place, so that a write that fails leaves nothing at `path`.
703	///
704	/// # Errors
705	///
706	/// Returns [`NodeError::PlaceTaken`] if something is at `path`, [`NodeError::NotHere`] if
707	/// this replica does not hold the JPEG, and [`NodeError::File`] if writing fails.
708	pub fn save_thumbnail(
709		&self,
710		space: SpaceId,
711		thumbnail: &ThumbnailOf,
712		path: &Path,
713	) -> Result<(), NodeError> {
714		if path.symlink_metadata().is_ok() {
715			return Err(NodeError::PlaceTaken(path.to_owned()));
716		}
717		let jpeg = self
718			.thumbnail_jpeg(space, thumbnail)?
719			.ok_or_else(|| NodeError::NotHere(thumbnail.content.to_string()))?;
720		let temporary = temporary_for(path, "thumbnail");
721		remove_leftover(&temporary);
722		let written = File::create_new(&temporary).and_then(|mut file| {
723			file.write_all(&jpeg)?;
724			file.sync_all()
725		});
726		if let Err(error) = written {
727			remove_leftover(&temporary);
728			return Err(NodeError::file(&temporary)(error));
729		}
730		if let Err(error) = put_in_place(&temporary, path) {
731			remove_leftover(&temporary);
732			if error.kind() == std::io::ErrorKind::AlreadyExists {
733				return Err(NodeError::PlaceTaken(path.to_owned()));
734			}
735			return Err(NodeError::file(path)(error));
736		}
737		Ok(())
738	}
739
740	/// How many of a space's files are pictures or videos, and how many of those have a
741	/// thumbnail.
742	///
743	/// # Errors
744	///
745	/// Returns an error if the library has no such space, or it cannot be read.
746	pub fn thumbnail_counts(&self, space: SpaceId) -> Result<ThumbnailCounts, NodeError> {
747		let with = self.contents_with_thumbnails(space)?;
748		let pictures = self.pictures(space)?;
749		Ok(ThumbnailCounts {
750			pictures: pictures.len(),
751			with: pictures
752				.keys()
753				.filter(|content| with.contains(*content))
754				.count(),
755		})
756	}
757
758	/// Whether a content of a space has a thumbnail, recorded and neither deleted nor moved
759	/// away.
760	fn has_thumbnail(&self, space: SpaceId, content: &Hash) -> Result<bool, NodeError> {
761		let open = self.space(space)?;
762		let state = open.stored.log().state();
763		for thumbnail in open.stored.find(&THUMBNAIL_OF, &Value::Blob(*content))? {
764			let thumbnail = state.canonical(thumbnail)?;
765			if state.types(thumbnail)?.contains(&THUMBNAIL)
766				&& !gone(state, thumbnail)?
767				&& blob_of(state, thumbnail, &CONTENT)?.is_some()
768			{
769				return Ok(true);
770			}
771		}
772		Ok(false)
773	}
774
775	/// The media type of a content of a space, if it is the current content of a file that is
776	/// neither gone nor a tree's, and an image or a video, as the file's media type says.
777	fn picture_type(&self, space: SpaceId, content: &Hash) -> Result<Option<String>, NodeError> {
778		let open = self.space(space)?;
779		let state = open.stored.log().state();
780		for file in open.stored.find(&CONTENT, &Value::Blob(*content))? {
781			let file = state.canonical(file)?;
782			if !state.types(file)?.contains(&FILE)
783				|| gone(state, file)?
784				|| !state.current(file, &IN_TREE)?.is_empty()
785			{
786				continue;
787			}
788			if let Some(media_type) = media_type_of(state, file)? {
789				return Ok(Some(media_type));
790			}
791		}
792		Ok(None)
793	}
794
795	/// The contents of a space that have a thumbnail, recorded and neither deleted nor moved
796	/// away.
797	fn contents_with_thumbnails(&self, space: SpaceId) -> Result<BTreeSet<Hash>, NodeError> {
798		let open = self.space(space)?;
799		let state = open.stored.log().state();
800		let mut with = BTreeSet::new();
801		for thumbnail in open
802			.stored
803			.find(&fields::TYPE, &Value::Text(THUMBNAIL.to_string()))?
804		{
805			let thumbnail = state.canonical(thumbnail)?;
806			if gone(state, thumbnail)? || blob_of(state, thumbnail, &CONTENT)?.is_none() {
807				continue;
808			}
809			with.extend(blob_of(state, thumbnail, &THUMBNAIL_OF)?);
810		}
811		Ok(with)
812	}
813
814	/// The files of a space whose current content is an image or a video, as its media type
815	/// says, but those of trees and those deleted or moved away: each content once.
816	fn pictures(&self, space: SpaceId) -> Result<BTreeMap<Hash, Picture>, NodeError> {
817		let open = self.space(space)?;
818		let state = open.stored.log().state();
819		let mut pictures = BTreeMap::new();
820		for file in open
821			.stored
822			.find(&fields::TYPE, &Value::Text(FILE.to_string()))?
823		{
824			let file = state.canonical(file)?;
825			if gone(state, file)? || !state.current(file, &IN_TREE)?.is_empty() {
826				continue;
827			}
828			let Some((content, statement)) =
829				state
830					.current(file, &CONTENT)?
831					.into_iter()
832					.find_map(|statement| match statement.value {
833						Value::Blob(content) => Some((content, statement.id)),
834						_ => None,
835					})
836			else {
837				continue;
838			};
839			let Some(media_type) = media_type_of(state, file)? else {
840				continue;
841			};
842			let taken = state
843				.current(file, &TAKEN)?
844				.first()
845				.and_then(|statement| match &statement.value {
846					Value::Date(taken) => match taken.start() {
847						Start::At { day, second } => Some((day, second.unwrap_or(0))),
848						Start::BeginningOfTime => None,
849					},
850					_ => None,
851				});
852			let recorded = state.storage().get(statement)?.and_then(|recorded| {
853				let millis = recorded.at.millis();
854				Day::from_unix_millis(millis, 0).map(|day| (day, Day::second_of_day(millis, 0)))
855			});
856			let Some(newest) = taken.or(recorded) else {
857				continue;
858			};
859			pictures.entry(content).or_insert(Picture {
860				content,
861				media_type,
862				newest,
863			});
864		}
865		Ok(pictures)
866	}
867}
868
869/// The version of a way of making thumbnails, as `std.made-with` ends with it, such as 1 of
870/// `nibkeep 1`; 0 if it names none.
871fn way_of(made_with: &str) -> u64 {
872	made_with
873		.rsplit(' ')
874		.next()
875		.and_then(|version| version.parse().ok())
876		.unwrap_or(0)
877}
878
879/// Whether an entity is gone from its space: deleted, or moved to another.
880pub(super) fn gone<S: Statements>(state: &State<S>, entity: EntityId) -> Result<bool, NodeError>
881where
882	NodeError: From<S::Error>,
883{
884	Ok(state.is_deleted(entity)? || !state.current(entity, &fields::MOVED_INTO)?.is_empty())
885}
886
887/// A file's media type, if it is an image's or a video's.
888fn media_type_of<S: Statements>(
889	state: &State<S>,
890	file: EntityId,
891) -> Result<Option<String>, NodeError>
892where
893	NodeError: From<S::Error>,
894{
895	Ok(state
896		.current(file, &MEDIA_TYPE)?
897		.first()
898		.and_then(|statement| statement.value.as_text().map(str::to_owned))
899		.filter(|media_type| media_type.starts_with("image/") || media_type.starts_with("video/")))
900}
901
902/// The first blob that an entity's field holds now.
903pub(super) fn blob_of<S: Statements>(
904	state: &State<S>,
905	entity: EntityId,
906	field: &FieldName,
907) -> Result<Option<Hash>, NodeError>
908where
909	NodeError: From<S::Error>,
910{
911	Ok(state
912		.current(entity, field)?
913		.into_iter()
914		.find_map(|statement| match statement.value {
915			Value::Blob(content) => Some(content),
916			_ => None,
917		}))
918}
919
920#[cfg(test)]
921mod tests {
922	use super::*;
923
924	#[test]
925	fn ways_are_told_by_their_versions() {
926		assert_eq!(way_of("nibkeep 1"), 1);
927		assert_eq!(way_of("nibkeep 12"), 12);
928		assert_eq!(way_of("nibkeep"), 0);
929		assert_eq!(way_of(""), 0);
930	}
931}