use super::*;
#[derive(Debug, Default, PartialEq, Eq)]
pub(crate) struct Purged {
pub uploads: Vec<String>,
pub scrubs: usize,
}
pub(crate) async fn purge_deleted_channel(community: &CommunityV2, channel_id: &ChannelId, deleted_by: Option<PublicKey>) -> Option<Purged> {
let (cid_hex, ch_hex) = (crate::simd::hex::bytes_to_hex_32(&community.id().0), crate::simd::hex::bytes_to_hex_32(&channel_id.0));
let events = match crate::db::community::channel_events(&ch_hex) {
Ok(events) => events,
Err(e) => {
crate::log_warn!("[Community] reading deleted channel {}: {e}", &ch_hex[..8]);
return None;
}
};
let mine: Vec<String> = events
.iter()
.map(|(id, _)| id)
.filter(|id| matches!(crate::db::community::has_wrap_owner(id), Ok(true)) || matches!(crate::db::community::has_message_key(id), Ok(true)))
.cloned()
.collect();
let mut files = Vec::new();
for (id, _) in events.iter().filter(|(_, has_files)| *has_files) {
if let Ok(Some((_, msg))) = crate::db::events::get_message_by_id(id).await {
files.push((id.clone(), msg.mine, msg.attachments));
}
}
let in_memory = {
let mut st = crate::state::STATE.lock().await;
let before = st.chats.len();
st.chats.retain(|c| c.id != ch_hex);
st.chats.len() != before
};
let held = match crate::db::community::forget_channel_chat(&cid_hex, &ch_hex) {
Ok(held) => held,
Err(e) => {
crate::log_warn!("[Community] forgetting deleted channel {}: {e}", &ch_hex[..8]);
return None;
}
};
if !held && !in_memory {
return None;
}
crate::community::v2::changes::note_channel_deleted(community, channel_id, deleted_by.as_ref());
let mut uploads = Vec::new();
for (id, mine, attachments) in files {
if mine {
uploads.extend(attachments.iter().flat_map(|a| a.all_urls().map(str::to_string)));
}
crate::deletion::delete_cached_attachment_files_pub(&crate::deletion::filter_unreferenced_attachments(&id, attachments).await);
}
let uploads = crate::db::attachments::urls_unreferenced_elsewhere(&uploads, "").unwrap_or_default();
if !uploads.is_empty() {
if let Ok(signer) = crate::signer::active_signer() {
crate::blossom::delete_blobs_best_effort(signer, uploads.clone());
}
}
crate::community::message_delete::queue_scrubs(&cid_hex, &mine);
crate::traits::emit_event("channel_purged", &serde_json::json!({ "community_id": cid_hex, "channel_id": ch_hex }));
Some(Purged { uploads, scrubs: mine.len() })
}