use std::path::{Path, PathBuf};
use async_trait::async_trait;
use laravel::http::client;
use laravel::time::ToSpan;
use sha1::{Digest, Sha1};
use crate::config::LaracardsConfig;
use crate::contracts::Background;
use crate::exceptions::RenderFailed;
fn hex(bytes: &[u8]) -> String {
bytes.iter().map(|byte| format!("{byte:02x}")).collect()
}
pub struct LocalBackground {
path: PathBuf,
}
impl LocalBackground {
pub fn new(path: impl Into<PathBuf>) -> Self {
Self { path: path.into() }
}
fn existing(&self) -> Option<&Path> {
self.path.is_file().then_some(self.path.as_path())
}
}
#[async_trait]
impl Background for LocalBackground {
async fn resolve(&self) -> laravel::Result<Option<PathBuf>> {
match self.existing() {
Some(path) => Ok(Some(path.to_path_buf())),
None => Err(RenderFailed::new(format!(
"Laracards: the background '{}' does not exist.",
self.path.display()
))
.into()),
}
}
fn fingerprint(&self) -> String {
match self.existing().and_then(|path| std::fs::read(path).ok()) {
Some(contents) => format!("local:{}", &hex(&Sha1::digest(contents))[..16]),
None => "local:missing".to_owned(),
}
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct NullBackground;
#[async_trait]
impl Background for NullBackground {
async fn resolve(&self) -> laravel::Result<Option<PathBuf>> {
Ok(None)
}
fn fingerprint(&self) -> String {
"none".to_owned()
}
}
pub struct UnsplashBackground {
query: String,
orientation: String,
width: u32,
cache_path: Option<PathBuf>,
access_key: Option<String>,
}
impl UnsplashBackground {
pub fn new(query: impl Into<String>) -> Self {
Self {
query: query.into(),
orientation: "landscape".to_owned(),
width: 1600,
cache_path: None,
access_key: None,
}
}
#[must_use]
pub fn orientation(mut self, orientation: impl Into<String>) -> Self {
self.orientation = orientation.into();
self
}
#[must_use]
pub fn width(mut self, width: u32) -> Self {
self.width = width;
self
}
#[must_use]
pub fn cache_path(mut self, cache_path: impl Into<PathBuf>) -> Self {
self.cache_path = Some(cache_path.into());
self
}
#[must_use]
pub fn access_key(mut self, access_key: impl Into<String>) -> Self {
self.access_key = Some(access_key.into());
self
}
fn cache_key(&self) -> String {
let digest = Sha1::digest(format!("{}|{}|{}", self.query, self.orientation, self.width));
hex(&digest)[..20].to_owned()
}
}
#[async_trait]
impl Background for UnsplashBackground {
async fn resolve(&self) -> laravel::Result<Option<PathBuf>> {
let config = LaracardsConfig::current();
let cache = self
.cache_path
.clone()
.unwrap_or_else(|| LaracardsConfig::resolve(&LaracardsConfig::base(), &config.backgrounds.unsplash.cache));
let cached = cache.join(format!("{}.jpg", self.cache_key()));
if cached.is_file() {
return Ok(Some(cached));
}
let Some(access_key) = self.access_key.clone().or(config.backgrounds.unsplash.access_key) else {
tracing::warn!(query = %self.query, "Laracards: no Unsplash access key configured, skipping background.");
return Ok(None);
};
std::fs::create_dir_all(&cache)?;
let search = client::get("https://api.unsplash.com/search/photos")
.header("Authorization", format!("Client-ID {access_key}"))
.header("Accept-Version", "v1")
.query([
("query", self.query.as_str()),
("orientation", self.orientation.as_str()),
("per_page", "1"),
])
.timeout(20.seconds())
.await?;
if !search.successful() {
tracing::warn!(query = %self.query, status = search.status().as_u16(), "Laracards: Unsplash search failed.");
return Ok(None);
}
let found: serde_json::Value = search.json()?;
let Some(url) = found["results"][0]["urls"]["raw"].as_str() else {
tracing::warn!(query = %self.query, "Laracards: Unsplash returned no results.");
return Ok(None);
};
let photo = client::get(format!("{url}&w={}&q=80&fm=jpg&fit=max", self.width))
.timeout(60.seconds())
.await?;
if !photo.successful() {
return Ok(None);
}
std::fs::write(&cached, photo.bytes())?;
Ok(Some(cached))
}
fn fingerprint(&self) -> String {
format!("unsplash:{}", self.cache_key())
}
}