| 1 |
use anyhow::{Result, anyhow, bail}; |
| 2 |
use glib::WeakRef; |
| 3 |
use gtk::gdk; |
| 4 |
use gtk::glib; |
| 5 |
use gtk::prelude::*; |
| 6 |
use std::collections::{HashMap, HashSet}; |
| 7 |
use std::io::Cursor; |
| 8 |
use std::path::PathBuf; |
| 9 |
use std::sync::LazyLock; |
| 10 |
use tokio::sync::RwLock; |
| 11 |
|
| 12 |
use crate::thumbnail_generator::ThumbSize; |
| 13 |
use podcasts_data::errors::DownloadError; |
| 14 |
use podcasts_data::errors::DownloadError::NoLongerNeeded; |
| 15 |
use podcasts_data::utils::get_cover_dir_path; |
| 16 |
use podcasts_data::xdg_dirs::TMP_DIR; |
| 17 |
use podcasts_data::{ShowCoverModel, ShowId}; |
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
static CACHE_VALID_DURATION: LazyLock<chrono::Duration> = |
| 41 |
LazyLock::new(|| chrono::Duration::weeks(4)); |
| 42 |
|
| 43 |
#[derive(Copy, Clone, Eq, Hash, PartialEq)] |
| 44 |
struct CoverId(ShowId, ThumbSize); |
| 45 |
|
| 46 |
impl From<CoverId> for (ShowId, ThumbSize) { |
| 47 |
fn from(cover_id: CoverId) -> (ShowId, ThumbSize) { |
| 48 |
let CoverId(id, size) = cover_id; |
| 49 |
(id, size) |
| 50 |
} |
| 51 |
} |
| 52 |
|
| 53 |
|
| 54 |
#[derive(Clone, Eq, Hash, PartialEq)] |
| 55 |
enum CachedTexture { |
| 56 |
Cached(gdk::Texture), |
| 57 |
FailedToLoad, |
| 58 |
} |
| 59 |
|
| 60 |
|
| 61 |
static COVER_TEXTURES: LazyLock<RwLock<HashMap<CoverId, CachedTexture>>> = |
| 62 |
LazyLock::new(|| RwLock::new(HashMap::new())); |
| 63 |
|
| 64 |
static COVER_DL_REGISTRY: LazyLock<RwLock<HashSet<ShowId>>> = |
| 65 |
LazyLock::new(|| RwLock::new(HashSet::new())); |
| 66 |
|
| 67 |
static THUMB_LOAD_REGISTRY: LazyLock<RwLock<HashSet<CoverId>>> = |
| 68 |
LazyLock::new(|| RwLock::new(HashSet::new())); |
| 69 |
|
| 70 |
fn filename_for_download(response: &reqwest::Response) -> String { |
| 71 |
let mime = response.headers().get(reqwest::header::CONTENT_TYPE); |
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
let headers = HashMap::from([ |
| 76 |
("image/apng", ".png"), |
| 77 |
("image/avif", ".avif"), |
| 78 |
("image/gif", ".gif"), |
| 79 |
("image/jpeg", ".jpeg"), |
| 80 |
("image/png", ".png"), |
| 81 |
("image/svg", ".svg"), |
| 82 |
("image/webp", ".webp"), |
| 83 |
]); |
| 84 |
|
| 85 |
let mime_extension = mime |
| 86 |
.and_then(|m| m.to_str().ok()) |
| 87 |
.and_then(|m| headers.get(m)) |
| 88 |
.unwrap_or(&""); |
| 89 |
|
| 90 |
|
| 91 |
let ext = response |
| 92 |
.url() |
| 93 |
.path_segments() |
| 94 |
.and_then(|segments| segments.last()) |
| 95 |
.unwrap_or("tmp-donwload.bin"); |
| 96 |
|
| 97 |
if ext.is_empty() { |
| 98 |
return ["tmp-donwload", mime_extension].join(""); |
| 99 |
} |
| 100 |
|
| 101 |
[ext, mime_extension].join("") |
| 102 |
} |
| 103 |
|
| 104 |
pub fn clean_unfinished_downloads() -> Result<()> { |
| 105 |
info!("Starting cover locks cleanup"); |
| 106 |
let dir = TMP_DIR.clone(); |
| 107 |
|
| 108 |
for entry in std::fs::read_dir(dir)? { |
| 109 |
|
| 110 |
match entry.map(|e| e.path()) { |
| 111 |
Ok(path) => { |
| 112 |
if let Err(err) = cleanup_entry(&path) { |
| 113 |
error!("failed to cleanup: {} {err}", path.display()); |
| 114 |
} |
| 115 |
} |
| 116 |
Err(err) => error!("failed to get path {err}"), |
| 117 |
} |
| 118 |
} |
| 119 |
|
| 120 |
Ok(()) |
| 121 |
} |
| 122 |
|
| 123 |
fn cleanup_entry(path: &PathBuf) -> Result<()> { |
| 124 |
if path.is_file() && path.ends_with(".part") { |
| 125 |
std::fs::remove_file(path)?; |
| 126 |
} |
| 127 |
|
| 128 |
if path.is_dir() { |
| 129 |
if let Some(filename) = path.to_str() { |
| 130 |
if filename.contains("-pdcover.part") { |
| 131 |
info!("Removing unfinished download: {}", path.display()); |
| 132 |
|
| 133 |
|
| 134 |
|
| 135 |
std::fs::remove_dir_all(path)?; |
| 136 |
} |
| 137 |
} |
| 138 |
} |
| 139 |
Ok(()) |
| 140 |
} |
| 141 |
|
| 142 |
|
| 143 |
|
| 144 |
|
| 145 |
pub fn determin_cover_path(pd: &ShowCoverModel, size: Option<ThumbSize>) -> PathBuf { |
| 146 |
let mut dir = get_cover_dir_path(pd.title()); |
| 147 |
if let Some(size) = size { |
| 148 |
dir.push(format!("cover-{size}")); |
| 149 |
} else { |
| 150 |
dir.push("cover"); |
| 151 |
}; |
| 152 |
dir |
| 153 |
} |
| 154 |
|
| 155 |
fn determin_cover_path_for_update(pd: &ShowCoverModel) -> PathBuf { |
| 156 |
let mut dir = get_cover_dir_path(pd.title()); |
| 157 |
let filename = format!("{}-update", pd.id().0); |
| 158 |
dir.push(filename); |
| 159 |
dir |
| 160 |
} |
| 161 |
|
| 162 |
async fn download( |
| 163 |
pd: &ShowCoverModel, |
| 164 |
cover_id: &CoverId, |
| 165 |
path: &PathBuf, |
| 166 |
just_download: bool, |
| 167 |
) -> Result<Option<CachedTexture>> { |
| 168 |
let url = pd |
| 169 |
.image_uri() |
| 170 |
.ok_or(anyhow!("invalid cover uri"))? |
| 171 |
.to_owned(); |
| 172 |
if url.is_empty() { |
| 173 |
bail!("No download location"); |
| 174 |
} |
| 175 |
|
| 176 |
|
| 177 |
let tmp_dir = tempfile::Builder::new() |
| 178 |
.suffix(&format!("{}-pdcover.part", pd.id().0)) |
| 179 |
.tempdir_in(&*TMP_DIR)?; |
| 180 |
let client = podcasts_data::downloader::client_builder().build()?; |
| 181 |
let uri = pd.image_uri().ok_or(anyhow!("No image uri for podcast"))?; |
| 182 |
let response = client.get(uri).send().await?; |
| 183 |
|
| 184 |
debug!("Status Resp: {}", response.status()); |
| 185 |
|
| 186 |
let filename = filename_for_download(&response); |
| 187 |
let filename = tmp_dir.path().join(filename); |
| 188 |
info!("Downloading file into: '{:?}'", filename); |
| 189 |
{ |
| 190 |
let mut dest = tokio::fs::File::create(&filename).await?; |
| 191 |
let mut content = Cursor::new(response.bytes().await?); |
| 192 |
tokio::io::copy(&mut content, &mut dest).await?; |
| 193 |
dest.sync_all().await?; |
| 194 |
} |
| 195 |
|
| 196 |
|
| 197 |
let thumbs = crate::thumbnail_generator::generate(pd, &filename).await?; |
| 198 |
|
| 199 |
if let Err(err) = pd.update_image_cache_values() { |
| 200 |
error!( |
| 201 |
"Failed to update cache date on Cover image: {err} for {}", |
| 202 |
path.display() |
| 203 |
); |
| 204 |
} |
| 205 |
|
| 206 |
if just_download { |
| 207 |
tokio::fs::rename(&filename, &path).await?; |
| 208 |
return Ok(None); |
| 209 |
} |
| 210 |
if let Some(thumb_texture) = thumbs.get(&cover_id.1) { |
| 211 |
info!("Cached img into: '{}'", &path.display()); |
| 212 |
let cached = CachedTexture::Cached(thumb_texture.clone()); |
| 213 |
COVER_TEXTURES |
| 214 |
.write() |
| 215 |
.await |
| 216 |
.insert(*cover_id, cached.clone()); |
| 217 |
|
| 218 |
|
| 219 |
|
| 220 |
tokio::fs::rename(&filename, &path).await?; |
| 221 |
return Ok(Some(cached)); |
| 222 |
} |
| 223 |
|
| 224 |
bail!("failed to generate thumbnails"); |
| 225 |
} |
| 226 |
|
| 227 |
async fn from_web( |
| 228 |
pd: &ShowCoverModel, |
| 229 |
cover_id: &CoverId, |
| 230 |
path: &PathBuf, |
| 231 |
) -> Result<CachedTexture> { |
| 232 |
let result = download(pd, cover_id, path, false).await; |
| 233 |
if let Ok(Some(texture)) = result { |
| 234 |
Ok(texture) |
| 235 |
} else { |
| 236 |
|
| 237 |
COVER_TEXTURES |
| 238 |
.write() |
| 239 |
.await |
| 240 |
.insert(*cover_id, CachedTexture::FailedToLoad); |
| 241 |
result.map(|_| CachedTexture::FailedToLoad) |
| 242 |
} |
| 243 |
} |
| 244 |
|
| 245 |
async fn cover_is_downloading(show_id: ShowId) -> bool { |
| 246 |
COVER_DL_REGISTRY.read().await.contains(&show_id) |
| 247 |
} |
| 248 |
|
| 249 |
const SLEEP_TIME: std::time::Duration = std::time::Duration::from_millis(250); |
| 250 |
const SLEEP_LIMIT: std::time::Duration = std::time::Duration::from_secs(30); |
| 251 |
async fn wait_for_download(pd: &ShowCoverModel, cover_id: &CoverId) -> Result<CachedTexture> { |
| 252 |
let mut time_waited = std::time::Duration::new(0, 0); |
| 253 |
while { |
| 254 |
|
| 255 |
tokio::time::sleep(SLEEP_TIME).await; |
| 256 |
time_waited += SLEEP_TIME; |
| 257 |
if time_waited > SLEEP_LIMIT { |
| 258 |
bail!("Waited too long for download."); |
| 259 |
} |
| 260 |
cover_is_downloading(cover_id.0).await |
| 261 |
} {} |
| 262 |
from_cache_or_fs(pd, cover_id).await |
| 263 |
} |
| 264 |
|
| 265 |
async fn from_cache_or_fs(pd: &ShowCoverModel, cover_id: &CoverId) -> Result<CachedTexture> { |
| 266 |
if let Some(texture) = from_cache(cover_id).await { |
| 267 |
Ok(texture) |
| 268 |
} else { |
| 269 |
|
| 270 |
if THUMB_LOAD_REGISTRY.read().await.contains(cover_id) { |
| 271 |
let mut time_waited = std::time::Duration::new(0, 0); |
| 272 |
while { |
| 273 |
|
| 274 |
tokio::time::sleep(std::time::Duration::from_millis(25)).await; |
| 275 |
time_waited += SLEEP_TIME; |
| 276 |
if time_waited > SLEEP_LIMIT { |
| 277 |
bail!("Waited too long for thumb read."); |
| 278 |
} |
| 279 |
THUMB_LOAD_REGISTRY.read().await.contains(cover_id) |
| 280 |
} {} |
| 281 |
return from_cache(cover_id) |
| 282 |
.await |
| 283 |
.ok_or(anyhow!("Failed to wait for thumbnail form cache.")); |
| 284 |
} |
| 285 |
let got_lock = THUMB_LOAD_REGISTRY.write().await.insert(*cover_id); |
| 286 |
if got_lock { |
| 287 |
let result = from_fs(pd, cover_id).await; |
| 288 |
THUMB_LOAD_REGISTRY.write().await.remove(cover_id); |
| 289 |
result |
| 290 |
} else { |
| 291 |
from_cache(cover_id).await.ok_or(anyhow!( |
| 292 |
"Failed to wait for thumbnail form cache (failed lock)." |
| 293 |
)) |
| 294 |
} |
| 295 |
} |
| 296 |
} |
| 297 |
|
| 298 |
async fn from_cache(cover_id: &CoverId) -> Option<CachedTexture> { |
| 299 |
COVER_TEXTURES.read().await.get(cover_id).cloned() |
| 300 |
} |
| 301 |
|
| 302 |
async fn from_fs(pd: &ShowCoverModel, cover_id: &CoverId) -> Result<CachedTexture> { |
| 303 |
let thumb = determin_cover_path(pd, Some(cover_id.1)); |
| 304 |
if let Ok(texture) = gdk::Texture::from_filename(thumb) { |
| 305 |
let cached = CachedTexture::Cached(texture); |
| 306 |
COVER_TEXTURES |
| 307 |
.write() |
| 308 |
.await |
| 309 |
.insert(*cover_id, cached.clone()); |
| 310 |
Ok(cached) |
| 311 |
} else { |
| 312 |
bail!("failed to load texture") |
| 313 |
} |
| 314 |
} |
| 315 |
|
| 316 |
async fn from_update( |
| 317 |
pd: &ShowCoverModel, |
| 318 |
cover_id: &CoverId, |
| 319 |
cover: &PathBuf, |
| 320 |
) -> Result<CachedTexture> { |
| 321 |
|
| 322 |
|
| 323 |
|
| 324 |
let update_path = determin_cover_path_for_update(pd); |
| 325 |
let texture = from_web(pd, cover_id, &update_path).await?; |
| 326 |
tokio::fs::rename(&update_path, &cover).await?; |
| 327 |
Ok(texture) |
| 328 |
} |
| 329 |
|
| 330 |
async fn aquire_dl_lock(show_id: ShowId) -> bool { |
| 331 |
COVER_DL_REGISTRY.write().await.insert(show_id) |
| 332 |
} |
| 333 |
async fn drop_dl_lock(show_id: ShowId) { |
| 334 |
COVER_DL_REGISTRY.write().await.remove(&show_id); |
| 335 |
} |
| 336 |
|
| 337 |
|
| 338 |
pub async fn just_download(pd: &ShowCoverModel) -> Result<()> { |
| 339 |
let show_id = pd.id(); |
| 340 |
if aquire_dl_lock(show_id).await { |
| 341 |
let cover = determin_cover_path(pd, None); |
| 342 |
|
| 343 |
let unused_cover_id = CoverId(show_id, crate::Thumb64); |
| 344 |
let result = download(pd, &unused_cover_id, &cover, true).await; |
| 345 |
drop_dl_lock(show_id).await; |
| 346 |
result?; |
| 347 |
} else { |
| 348 |
while { |
| 349 |
|
| 350 |
tokio::time::sleep(std::time::Duration::from_millis(250)).await; |
| 351 |
cover_is_downloading(show_id).await |
| 352 |
} {} |
| 353 |
} |
| 354 |
Ok(()) |
| 355 |
} |
| 356 |
|
| 357 |
async fn load_texture(pd: &ShowCoverModel, thumb_size: ThumbSize) -> Result<CachedTexture> { |
| 358 |
if pd.image_uri().is_none() { |
| 359 |
bail!("no image_uri for this show: {}", pd.title()); |
| 360 |
} |
| 361 |
let show_id = pd.id(); |
| 362 |
let cover_id = CoverId(show_id, thumb_size); |
| 363 |
|
| 364 |
if let Some(texture) = from_cache(&cover_id).await { |
| 365 |
return Ok(texture); |
| 366 |
} |
| 367 |
|
| 368 |
if cover_is_downloading(show_id).await { |
| 369 |
return wait_for_download(pd, &cover_id).await; |
| 370 |
} |
| 371 |
|
| 372 |
if !aquire_dl_lock(show_id).await { |
| 373 |
return wait_for_download(pd, &cover_id).await; |
| 374 |
} |
| 375 |
|
| 376 |
if !pd.is_cached_image_valid(&CACHE_VALID_DURATION) { |
| 377 |
let cover = determin_cover_path(pd, None); |
| 378 |
let result = from_update(pd, &cover_id, &cover).await; |
| 379 |
let result = if let Err(err) = result { |
| 380 |
warn!("Failed to update cover, reusing the already download one. {err}"); |
| 381 |
from_fs(pd, &cover_id).await |
| 382 |
} else { |
| 383 |
result |
| 384 |
}; |
| 385 |
drop_dl_lock(show_id).await; |
| 386 |
return result; |
| 387 |
} |
| 388 |
|
| 389 |
if let Ok(texture) = from_fs(pd, &cover_id).await { |
| 390 |
drop_dl_lock(show_id).await; |
| 391 |
return Ok(texture); |
| 392 |
} |
| 393 |
|
| 394 |
let cover = determin_cover_path(pd, None); |
| 395 |
let thumb = determin_cover_path(pd, Some(thumb_size)); |
| 396 |
let cover_exists = cover.exists(); |
| 397 |
|
| 398 |
|
| 399 |
if !thumb.exists() && cover_exists { |
| 400 |
warn!( |
| 401 |
"Cover exists, but thumb is missing, Maybe Download was broken. Redownloading Cover!" |
| 402 |
); |
| 403 |
let result = from_update(pd, &cover_id, &cover).await; |
| 404 |
drop_dl_lock(show_id).await; |
| 405 |
return result; |
| 406 |
} |
| 407 |
|
| 408 |
if !cover_exists { |
| 409 |
info!("Downloading cover: {}", cover.display()); |
| 410 |
let result = from_web(pd, &cover_id, &cover).await; |
| 411 |
drop_dl_lock(show_id).await; |
| 412 |
result |
| 413 |
} else { |
| 414 |
drop_dl_lock(show_id).await; |
| 415 |
bail!("The cover exists, but we can't load it?") |
| 416 |
} |
| 417 |
} |
| 418 |
|
| 419 |
pub trait TextureWidget { |
| 420 |
fn set_from_texture(&self, texture: &gdk::Texture); |
| 421 |
} |
| 422 |
|
| 423 |
impl TextureWidget for gtk::Image { |
| 424 |
fn set_from_texture(&self, texture: &gdk::Texture) { |
| 425 |
self.set_paintable(Some(texture)); |
| 426 |
} |
| 427 |
} |
| 428 |
|
| 429 |
impl TextureWidget for gtk::Picture { |
| 430 |
fn set_from_texture(&self, texture: &gdk::Texture) { |
| 431 |
self.set_paintable(Some(texture)); |
| 432 |
} |
| 433 |
} |
| 434 |
|
| 435 |
async fn load_paintable_async<T>( |
| 436 |
image: &WeakRef<T>, |
| 437 |
podcast_id: ShowId, |
| 438 |
size: ThumbSize, |
| 439 |
set_tooltip: bool, |
| 440 |
) -> Result<()> |
| 441 |
where |
| 442 |
T: TextureWidget + IsA<gtk::Widget>, |
| 443 |
{ |
| 444 |
use podcasts_data::dbqueries; |
| 445 |
|
| 446 |
let pd = crate::RUNTIME |
| 447 |
.spawn_blocking(move || dbqueries::get_podcast_cover_from_id(podcast_id).unwrap()) |
| 448 |
.await?; |
| 449 |
|
| 450 |
if set_tooltip { |
| 451 |
if let Some(image) = image.upgrade() { |
| 452 |
image.set_tooltip_text(Some(pd.title())); |
| 453 |
} else { |
| 454 |
return Err(NoLongerNeeded.into()); |
| 455 |
} |
| 456 |
} |
| 457 |
|
| 458 |
let result = crate::RUNTIME |
| 459 |
.spawn(async move { load_texture(&pd, size).await }) |
| 460 |
.await; |
| 461 |
|
| 462 |
match result { |
| 463 |
Ok(Ok(CachedTexture::Cached(texture))) => { |
| 464 |
if let Some(image) = image.upgrade() { |
| 465 |
image.set_from_texture(&texture); |
| 466 |
return Ok(()); |
| 467 |
} |
| 468 |
Err(NoLongerNeeded.into()) |
| 469 |
} |
| 470 |
Ok(Ok(CachedTexture::FailedToLoad)) => { |
| 471 |
bail!("Ignoring cover after failure to load. {podcast_id:#?}") |
| 472 |
} |
| 473 |
Ok(Err(err)) => bail!("Failed to load Show Cover: {err}"), |
| 474 |
Err(err) => bail!("Failed to load Show Cover with thread-error: {err}"), |
| 475 |
} |
| 476 |
} |
| 477 |
|
| 478 |
pub fn load_widget_texture<T>( |
| 479 |
widget: &T, |
| 480 |
show_id: ShowId, |
| 481 |
size: ThumbSize, |
| 482 |
set_tooltip: bool, |
| 483 |
) -> glib::JoinHandle<()> |
| 484 |
where |
| 485 |
T: TextureWidget + IsA<gtk::Widget>, |
| 486 |
{ |
| 487 |
|
| 488 |
|
| 489 |
let size = size.hidpi(widget.scale_factor()).unwrap_or(crate::Thumb512); |
| 490 |
let widget = widget.downgrade(); |
| 491 |
crate::MAINCONTEXT.spawn_local_with_priority(glib::source::Priority::LOW, async move { |
| 492 |
if let Err(err) = load_paintable_async(&widget, show_id, size, set_tooltip).await { |
| 493 |
if let Some(DownloadError::NoLongerNeeded) = err.downcast_ref::<DownloadError>() { |
| 494 |
|
| 495 |
return; |
| 496 |
} |
| 497 |
error!("Failed to load image: {err}"); |
| 498 |
} |
| 499 |
}) |
| 500 |
} |