1use 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
34pub const MOST_PICTURE_BYTES: u64 = 256 * 1024 * 1024;
36
37const MOST_BYTES_IN_FLIGHT: u64 = 96 * 1024 * 1024;
41
42const STUCK: std::time::Duration = std::time::Duration::from_secs(60);
46
47pub trait Thumbnailer: Send + Sync {
52 fn made_with(&self) -> &str;
55
56 fn reads(&self, media_type: &str) -> bool;
59
60 fn make(&self, picture: &[u8]) -> Option<Thumbnail>;
63}
64
65#[derive(Clone, PartialEq, Eq)]
68pub struct Thumbnail {
69 pub jpeg: Vec<u8>,
71 pub width: u32,
73 pub height: u32,
75 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
98pub struct ThumbnailsMade {
99 pub made: usize,
101 pub unreadable: usize,
104 pub not_here: usize,
107 pub copies_linked: usize,
109 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#[derive(Clone, Debug, PartialEq, Eq)]
126pub struct ThumbnailOf {
127 pub entity: EntityId,
129 pub content: Hash,
131 pub size: Option<(u32, u32)>,
133 pub made_with: Option<String>,
135 pub held: bool,
137}
138
139#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
142pub struct ThumbnailCounts {
143 pub pictures: usize,
145 pub with: usize,
147}
148
149type Jobs = mpsc::SyncSender<(Hash, Vec<u8>)>;
151
152type Results = mpsc::Receiver<(Hash, u64, Option<Thumbnail>)>;
155
156struct Picture {
158 content: Hash,
159 media_type: String,
160 newest: (Day, u32),
163}
164
165impl Library {
166 pub fn make_thumbnails_with(&mut self, thumbnailer: Arc<dyn Thumbnailer>) {
169 self.thumbnailer = Some(thumbnailer);
170 }
171
172 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 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 let Ok(job) = jobs.lock().map(|jobs| jobs.recv()) else {
232 return;
233 };
234 let Ok((content, picture)) = job else {
235 return;
236 };
237 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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
869fn 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
879pub(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
887fn 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
902pub(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}