use std::collections::BTreeMap;
use std::sync::Arc;
use adk_core::{AdkError, ErrorCategory, ErrorComponent, Result, Tool};
use adk_harness::website::{AuthoringRoute, AuthoringRouter, SiteRuntime, back_office_tools};
use adk_kernel::channels::{ChannelInbound, InboundBody};
use awp_types::ContentId;
use base64::Engine as _;
use bytes::Bytes;
use serde::{Deserialize, Serialize};
use serde_json::json;
use tokio::sync::Mutex;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChannelPhoto {
pub name: String,
pub bytes: Bytes,
pub caption: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PendingAlt {
pub item: ContentId,
pub path: String,
pub alt: String,
pub confirmed: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Attached {
pub photos: Vec<PendingAlt>,
pub reply: String,
}
pub struct OwnerChannel {
runtime: Arc<SiteRuntime>,
router: AuthoringRouter,
intake: Arc<dyn Tool>,
pending: Mutex<BTreeMap<String, Vec<PendingAlt>>>,
}
impl std::fmt::Debug for OwnerChannel {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("OwnerChannel").finish_non_exhaustive()
}
}
fn refused(code: &'static str, message: impl Into<String>) -> AdkError {
AdkError::new(ErrorComponent::Tool, ErrorCategory::Forbidden, code, message)
}
impl OwnerChannel {
pub fn new(runtime: Arc<SiteRuntime>, router: AuthoringRouter) -> Result<Self> {
let intake = back_office_tools(&runtime)
.into_iter()
.find(|tool| tool.name() == adk_harness::website::MEDIA_INTAKE)
.ok_or_else(|| AdkError::config("the back office has no media intake"))?;
Ok(Self { runtime, router, intake, pending: Mutex::new(BTreeMap::new()) })
}
async fn paired(&self, inbound: &ChannelInbound) -> Result<String> {
match self.router.route(inbound).await? {
AuthoringRoute::Owner { user_id, .. } => Ok(user_id),
AuthoringRoute::Public { .. } => Err(refused(
"website.channel.unpaired",
"only a device the owner paired adds media to the site (spec 3.5 A-I24)",
)),
}
}
pub async fn attach(
&self,
inbound: &ChannelInbound,
draft: &str,
item: &ContentId,
title: &str,
photos: Vec<ChannelPhoto>,
) -> Result<Attached> {
let person = self.paired(inbound).await?;
let ctx =
Arc::new(adk_tool::SimpleToolContext::new(format!("{}:{person}", inbound.channel)));
let mut attached = Vec::new();
for (n, photo) in photos.into_iter().enumerate() {
let alt = photo
.caption
.as_deref()
.map(str::trim)
.filter(|caption| !caption.is_empty())
.map_or_else(|| format!("{title}, photo {}", n + 1), str::to_string);
let args = json!({
"draft": draft,
"item": item.0,
"name": photo.name,
"dataBase64": base64::engine::general_purpose::STANDARD.encode(&photo.bytes),
"alt": alt,
});
let path = match self.intake.execute(ctx.clone(), args).await {
Ok(out) => out["media"]["path"].as_str().unwrap_or_default().to_string(),
Err(error) => match self.attach_to_scheduled(item, &photo, &alt).await? {
Some(path) => path,
None => return Err(error),
},
};
attached.push(PendingAlt { item: item.clone(), path, alt, confirmed: false });
}
self.pending
.lock()
.await
.entry(inbound.thread.clone())
.or_default()
.extend(attached.clone());
let mut reply = format!(
"Added {} photo{} to {title}. Their descriptions for people who cannot see them:",
attached.len(),
if attached.len() == 1 { "" } else { "s" }
);
for (n, photo) in attached.iter().enumerate() {
reply.push_str(&format!("\n{}: {}", n + 1, photo.alt));
}
reply.push_str("\nReply yes to confirm them, or a number and new text to change one.");
Ok(Attached { photos: attached, reply })
}
async fn attach_to_scheduled(
&self,
item: &ContentId,
photo: &ChannelPhoto,
alt: &str,
) -> Result<Option<String>> {
let site = |e: adk_site::SiteError| AdkError::config(e.to_string());
let store = self.runtime.store();
let Some(mut stored) = store.get(item).await.map_err(site)? else { return Ok(None) };
if !matches!(
stored.state,
awp_types::ContentState::Scheduled | awp_types::ContentState::Draft
) {
return Ok(None);
}
let processed = adk_site::media::MediaPipeline::default()
.process(&adk_site::media::MediaUpload {
name: &photo.name,
bytes: &photo.bytes,
alt: Some(alt.to_string()),
generated: false,
})
.map_err(site)?;
let dir =
format!("content/{}/{}", adk_site::content::kind_directory(stored.kind), stored.slug);
let media = processed.media_ref(&dir);
store.write_media(&media.path, processed.bytes.clone()).await.map_err(site)?;
for variant in &processed.variants {
store
.write_media(&format!("{dir}/{}", variant.name), variant.bytes.clone())
.await
.map_err(site)?;
}
stored.media.retain(|held| held.path != media.path);
stored.media.push(media.clone());
store.put(&stored).await.map_err(site)?;
Ok(Some(media.path))
}
pub async fn reply(&self, inbound: &ChannelInbound) -> Result<Option<String>> {
let text = match &inbound.body {
InboundBody::Text { text } => text.trim().to_string(),
_ => return Ok(None),
};
if !self.pending.lock().await.contains_key(&inbound.thread) {
return Ok(None);
}
self.paired(inbound).await?;
let lower = text.to_lowercase();
let answer = {
let mut pending = self.pending.lock().await;
let Some(photos) = pending.get_mut(&inbound.thread) else { return Ok(None) };
if matches!(lower.as_str(), "yes" | "y" | "ok" | "okay" | "confirm" | "confirmed") {
for photo in photos.iter_mut() {
photo.confirmed = true;
}
"Thank you: the descriptions are confirmed.".to_string()
} else if let Some((number, alt)) = text.split_once(':')
&& let Ok(n) = number.trim().parse::<usize>()
&& (1..=photos.len()).contains(&n)
&& !alt.trim().is_empty()
{
let photo = &mut photos[n - 1];
photo.alt = alt.trim().to_string();
photo.confirmed = true;
format!("Photo {n} now reads: {}", photo.alt)
} else {
return Ok(None);
}
};
self.settle().await?;
Ok(Some(answer))
}
pub async fn settle(&self) -> Result<usize> {
let mut pending = self.pending.lock().await;
let store = self.runtime.store();
let site = |e: adk_site::SiteError| AdkError::config(e.to_string());
let mut applied = 0;
for photos in pending.values_mut() {
let mut kept = Vec::new();
for photo in photos.drain(..) {
if !photo.confirmed {
kept.push(photo);
continue;
}
let Some(mut item) = store.get(&photo.item).await.map_err(site)? else {
kept.push(photo);
continue;
};
let Some(media) = item.media.iter_mut().find(|m| m.path == photo.path) else {
kept.push(photo);
continue;
};
media.alt = Some(photo.alt.clone());
media.alt_confirmed = true;
store.put(&item).await.map_err(site)?;
applied += 1;
}
*photos = kept;
}
pending.retain(|_, photos| !photos.is_empty());
Ok(applied)
}
pub async fn waiting(&self, thread: &str) -> Vec<PendingAlt> {
self.pending.lock().await.get(thread).cloned().unwrap_or_default()
}
}