use std::convert::TryInto; use log::error; use matrix_sdk::{ self, async_trait, events::{ room::message::{MessageEventContent, MessageType, TextMessageEventContent}, AnyMessageEventContent, SyncMessageEvent, }, room::Room, EventHandler, }; use crieur_retrieve::{article_location::Error, article_location::Result, ArticleLocation, Url}; pub(crate) struct Html {} impl Html { pub fn new() -> Self { Self {} } } async fn send_article(url: U, room: matrix_sdk::room::Joined) where U: TryInto + Send, E: std::error::Error + Sync + Send + 'static, { //TODO: replace by async block when async block is stable async fn article_html(url: U) -> Result where U: TryInto + Send, E: std::error::Error + Sync + Send + 'static, { let article_str = ArticleLocation::builder() .url(url)? .build()? .retrieve_html() .await?; Ok(article_str) } let text_message = |message| AnyMessageEventContent::RoomMessage(MessageEventContent::text_plain(message)); //TODO: replace occurences ok() by async and logging block when async block is stable let article_html = match article_html(url).await { Ok(url) => url, Err(Error::MalformedUrl) => { room.send(text_message("Error: Given url is malformed"), None) .await .ok(); return; } Err(Error::UnknownNewspaper) => { room.send( text_message("Error: Given url is do not correspond to a known newspaper"), None, ) .await .ok(); return; } Err(Error::Misconfiguration(key)) => { error!( "Error in configuration : {} key is missing or malformed", &key ); room.send( text_message("Error: configuration error, please contact your admin"), None, ) .await .ok(); return; } Err(_) => { room.send( text_message("Unknown error =/, can't download the file"), None, ) .await .ok(); return; } }; room.send_attachment( "article.html", &mime::TEXT_HTML_UTF_8, &mut article_html.as_bytes(), None, ) .await .ok(); } #[async_trait] impl EventHandler for Html { async fn on_room_message(&self, room: Room, event: &SyncMessageEvent) { if let Room::Joined(room) = room { let msg_body = if let SyncMessageEvent { content: MessageEventContent { msgtype: MessageType::Text(TextMessageEventContent { body: msg_body, .. }), .. }, .. } = event { msg_body } else { return; }; match msg_body.split(' ').collect::>().as_slice() { ["!html", url, ..] => send_article(*url, room).await, _ => return, } } } }