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