BlueGit

ict rusty-teams

Files

rusty-teams / crates / core / src / images.rs

images.rs

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