| 1 | use std::path::{Path, PathBuf}; |
| 2 | |
| 3 | use chrono::Utc; |
| 4 | use store::{ImageFileCache, ImageRecord}; |
| 5 | |
| 6 | use crate::engine::SyncEngine; |
| 7 | use crate::error::Result; |
| 8 | use crate::events::CoreEvent; |
| 9 | use crate::image_size::sniff; |
| 10 | use crate::remote::Remote; |
| 11 | use crate::stored::ImageRef; |
| 12 | |
| 13 | pub const IMAGE_CACHE_MAX_BYTES: u64 = 200 * 1024 * 1024; |
| 14 | |
| 15 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 16 | pub struct StoredImage { |
| 17 | pub bytes: Vec<u8>, |
| 18 | pub content_type: String, |
| 19 | pub width: Option<u32>, |
| 20 | pub height: Option<u32>, |
| 21 | } |
| 22 | |
| 23 | impl<R: Remote> SyncEngine<R> { |
| 24 | /// Keeps downloaded images as files in `directory` (least recently used evicted above `max_total_bytes`) instead of the database. |
| 25 | pub fn with_image_dir(mut self, directory: &Path, max_total_bytes: u64) -> Result<Self> { |
| 26 | self.image_files = Some(ImageFileCache::open(directory, max_total_bytes)?); |
| 27 | Ok(self) |
| 28 | } |
| 29 | |
| 30 | /// Cached file of the image, `None` when not downloaded yet or no image directory is set. |
| 31 | pub fn image_path(&self, image: &ImageRef) -> Option<PathBuf> { |
| 32 | self.image_files.as_ref()?.path(image.key()) |
| 33 | } |
| 34 | |
| 35 | pub fn image(&self, key: &str) -> Option<StoredImage> { |
| 36 | let (bytes, content_type) = match &self.image_files { |
| 37 | Some(files) => (std::fs::read(files.path(key)?).ok()?, String::new()), |
| 38 | None => { |
| 39 | let record = self.store.image(key).ok().flatten()?; |
| 40 | (record.bytes, record.content_type) |
| 41 | } |
| 42 | }; |
| 43 | let size = sniff(&bytes); |
| 44 | Some(StoredImage { |
| 45 | content_type: if content_type.is_empty() { |
| 46 | size.as_ref() |
| 47 | .map_or_else(String::new, |info| info.content_type.to_owned()) |
| 48 | } else { |
| 49 | content_type |
| 50 | }, |
| 51 | width: size.as_ref().map(|info| info.width), |
| 52 | height: size.as_ref().map(|info| info.height), |
| 53 | bytes, |
| 54 | }) |
| 55 | } |
| 56 | |
| 57 | /// Downloads once. Returns the local file when an image directory is set; `None` when another fetch of the same image is running. |
| 58 | /// Emits `ImagesChanged` once stored. |
| 59 | pub async fn fetch_image(&self, image: &ImageRef) -> Result<Option<PathBuf>> { |
| 60 | let key = image.key(); |
| 61 | if let Some(path) = self.image_path(image) { |
| 62 | return Ok(Some(path)); |
| 63 | } |
| 64 | if self.image_files.is_none() && self.store.has_image(key)? { |
| 65 | return Ok(None); |
| 66 | } |
| 67 | if !self.claim_image(key) { |
| 68 | return Ok(None); |
| 69 | } |
| 70 | let outcome = self.download_image(key).await; |
| 71 | self.release_image(key); |
| 72 | outcome |
| 73 | } |
| 74 | |
| 75 | async fn download_image(&self, key: &str) -> Result<Option<PathBuf>> { |
| 76 | let photo = self.remote.hosted_content(key).await?; |
| 77 | let path = match &self.image_files { |
| 78 | Some(files) => { |
| 79 | let extension = file_extension(&photo.content_type, &photo.bytes); |
| 80 | Some(files.put(key, &photo.bytes, extension)?) |
| 81 | } |
| 82 | None => { |
| 83 | self.store.put_image( |
| 84 | &ImageRecord { |
| 85 | key: key.to_owned(), |
| 86 | bytes: photo.bytes, |
| 87 | content_type: photo.content_type, |
| 88 | fetched_at: Utc::now(), |
| 89 | }, |
| 90 | IMAGE_CACHE_MAX_BYTES, |
| 91 | )?; |
| 92 | None |
| 93 | } |
| 94 | }; |
| 95 | let _ = self.events.send(CoreEvent::ImagesChanged { |
| 96 | keys: vec![key.to_owned()], |
| 97 | }); |
| 98 | Ok(path) |
| 99 | } |
| 100 | |
| 101 | fn claim_image(&self, key: &str) -> bool { |
| 102 | self.images_in_flight |
| 103 | .lock() |
| 104 | .unwrap_or_else(|poisoned| poisoned.into_inner()) |
| 105 | .insert(key.to_owned()) |
| 106 | } |
| 107 | |
| 108 | fn release_image(&self, key: &str) { |
| 109 | self.images_in_flight |
| 110 | .lock() |
| 111 | .unwrap_or_else(|poisoned| poisoned.into_inner()) |
| 112 | .remove(key); |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | fn file_extension(content_type: &str, bytes: &[u8]) -> &'static str { |
| 117 | let kind = if content_type.is_empty() { |
| 118 | sniff(bytes).map_or("", |info| info.content_type) |
| 119 | } else { |
| 120 | content_type |
| 121 | }; |
| 122 | match kind { |
| 123 | "image/png" => "png", |
| 124 | "image/jpeg" | "image/jpg" => "jpg", |
| 125 | "image/gif" => "gif", |
| 126 | "image/webp" => "webp", |
| 127 | "image/bmp" => "bmp", |
| 128 | _ => "bin", |
| 129 | } |
| 130 | } |