Update download error processing

This commit is contained in:
2024-05-07 19:29:40 +02:00
parent 34890449a1
commit 3c8fdb35eb
2 changed files with 50 additions and 110 deletions

View File

@@ -24,7 +24,7 @@ use crate::{
services::{ services::{
batch_downloader::{create_task, get_task, CreateTaskData, Task, TaskObjectType, TaskStatus}, batch_downloader::{create_task, get_task, CreateTaskData, Task, TaskObjectType, TaskStatus},
book_cache::{ book_cache::{
download_file, download_file_by_link, get_cached_message, get_download_link, download_file, download_file_by_link, get_cached_message,
types::{CachedMessage, DownloadFile}, types::{CachedMessage, DownloadFile},
}, },
book_library::{ book_library::{
@@ -85,20 +85,27 @@ async fn send_cached_message(
need_delete_message: bool, need_delete_message: bool,
cache: BotCache, cache: BotCache,
) -> BotHandlerInternal { ) -> BotHandlerInternal {
if let Ok(v) = get_cached_message(&download_data, cache).await { 'cached: {
if _send_cached(&message, &bot, v).await.is_ok() { if let Ok(v) = get_cached_message(&download_data, cache).await {
if need_delete_message { let cached = match v {
bot.delete_message(message.chat.id, message.id).await?; Some(v) => v,
} None => break 'cached,
};
match send_donation_notification(bot.clone(), message).await { if _send_cached(&message, &bot, cached).await.is_ok() {
Ok(_) => (), if need_delete_message {
Err(err) => log::error!("{:?}", err), bot.delete_message(message.chat.id, message.id).await?;
} }
return Ok(()); match send_donation_notification(bot.clone(), message).await {
} Ok(_) => (),
}; Err(err) => log::error!("{:?}", err),
}
return Ok(());
}
};
}
send_with_download_from_channel(message, bot, download_data, need_delete_message).await?; send_with_download_from_channel(message, bot, download_data, need_delete_message).await?;
@@ -140,6 +147,7 @@ async fn _send_downloaded_file(
Ok(()) Ok(())
} }
async fn send_with_download_from_channel( async fn send_with_download_from_channel(
message: Message, message: Message,
bot: CacheMe<Throttle<Bot>>, bot: CacheMe<Throttle<Bot>>,
@@ -148,14 +156,16 @@ async fn send_with_download_from_channel(
) -> BotHandlerInternal { ) -> BotHandlerInternal {
match download_file(&download_data).await { match download_file(&download_data).await {
Ok(v) => { Ok(v) => {
if _send_downloaded_file(&message, bot.clone(), v) let download_file = match v {
.await Some(v) => v,
.is_err() None => {
{ log::error!("File not found");
send_download_link(message.clone(), bot.clone(), download_data).await?; return Ok(());
return Ok(()); },
}; };
_send_downloaded_file(&message, bot.clone(), download_file).await?;
if need_delete_message { if need_delete_message {
bot.delete_message(message.chat.id, message.id).await?; bot.delete_message(message.chat.id, message.id).await?;
} }
@@ -166,36 +176,6 @@ async fn send_with_download_from_channel(
} }
} }
async fn send_download_link(
message: Message,
bot: CacheMe<Throttle<Bot>>,
download_data: DownloadQueryData,
) -> BotHandlerInternal {
let link_data = match get_download_link(&download_data).await {
Ok(v) => v,
Err(err) => {
log::error!("{:?}", err);
return Err(err);
}
};
bot.edit_message_text(
message.chat.id,
message.id,
format!(
"Файл не может быть загружен в чат! \n \
Вы можете скачать его <a href=\"{}\">по ссылке</a> (работает 3 часа)",
link_data.link
),
)
.parse_mode(ParseMode::Html)
.reply_markup(InlineKeyboardMarkup {
inline_keyboard: vec![],
})
.await?;
Ok(())
}
async fn download_handler( async fn download_handler(
message: Message, message: Message,
@@ -424,7 +404,13 @@ async fn wait_archive(
) )
.await .await
{ {
Ok(v) => v, Ok(v) => match v {
Some(v) => v,
None => {
send_error_message(bot, message.chat.id, message.id).await;
return Ok(());
},
},
Err(err) => { Err(err) => {
send_error_message(bot, message.chat.id, message.id).await; send_error_message(bot, message.chat.id, message.id).await;
log::error!("{:?}", err); log::error!("{:?}", err);

View File

@@ -1,30 +1,17 @@
use base64::{engine::general_purpose, Engine}; use base64::{engine::general_purpose, Engine};
use reqwest::StatusCode; use reqwest::StatusCode;
use std::fmt;
use crate::{bots::approved_bot::modules::download::callback_data::DownloadQueryData, bots_manager::BotCache, config}; use crate::{bots::approved_bot::modules::download::callback_data::DownloadQueryData, bots_manager::BotCache, config};
use self::types::{CachedMessage, DownloadFile, DownloadLink}; use self::types::{CachedMessage, DownloadFile};
pub mod types; pub mod types;
#[derive(Debug, Clone)]
struct DownloadError {
status_code: StatusCode,
}
impl fmt::Display for DownloadError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Status code is {0}", self.status_code)
}
}
impl std::error::Error for DownloadError {}
pub async fn get_cached_message( pub async fn get_cached_message(
download_data: &DownloadQueryData, download_data: &DownloadQueryData,
bot_cache: BotCache, bot_cache: BotCache,
) -> Result<CachedMessage, Box<dyn std::error::Error + Send + Sync>> { ) -> Result<Option<CachedMessage>, Box<dyn std::error::Error + Send + Sync>> {
let DownloadQueryData::DownloadData { let DownloadQueryData::DownloadData {
book_id: id, book_id: id,
file_type: format, file_type: format,
@@ -43,46 +30,17 @@ pub async fn get_cached_message(
.await? .await?
.error_for_status()?; .error_for_status()?;
if response.status() != StatusCode::OK { if response.status() == StatusCode::NO_CONTENT {
return Err(Box::new(DownloadError { return Ok(None);
status_code: response.status(),
}));
}; };
Ok(response.json::<CachedMessage>().await?) Ok(Some(response.json::<CachedMessage>().await?))
} }
pub async fn get_download_link(
download_data: &DownloadQueryData,
) -> Result<DownloadLink, Box<dyn std::error::Error + Send + Sync>> {
let DownloadQueryData::DownloadData {
book_id: id,
file_type: format,
} = download_data;
let client = reqwest::Client::new();
let response = client
.get(format!(
"{}/api/v1/link/{id}/{format}/",
&config::CONFIG.cache_server_url
))
.header("Authorization", &config::CONFIG.cache_server_api_key)
.send()
.await?
.error_for_status()?;
if response.status() != StatusCode::OK {
return Err(Box::new(DownloadError {
status_code: response.status(),
}));
};
Ok(response.json::<DownloadLink>().await?)
}
pub async fn download_file( pub async fn download_file(
download_data: &DownloadQueryData, download_data: &DownloadQueryData,
) -> Result<DownloadFile, Box<dyn std::error::Error + Send + Sync>> { ) -> Result<Option<DownloadFile>, Box<dyn std::error::Error + Send + Sync>> {
let DownloadQueryData::DownloadData { let DownloadQueryData::DownloadData {
book_id: id, book_id: id,
file_type: format, file_type: format,
@@ -98,10 +56,8 @@ pub async fn download_file(
.await? .await?
.error_for_status()?; .error_for_status()?;
if response.status() != StatusCode::OK { if response.status() == StatusCode::NO_CONTENT {
return Err(Box::new(DownloadError { return Ok(None);
status_code: response.status(),
}));
}; };
let headers = response.headers(); let headers = response.headers();
@@ -124,17 +80,17 @@ pub async fn download_file(
.unwrap() .unwrap()
.to_string(); .to_string();
Ok(DownloadFile { Ok(Some(DownloadFile {
response, response,
filename, filename,
caption, caption,
}) }))
} }
pub async fn download_file_by_link( pub async fn download_file_by_link(
filename: String, filename: String,
link: String, link: String,
) -> Result<DownloadFile, Box<dyn std::error::Error + Send + Sync>> { ) -> Result<Option<DownloadFile>, Box<dyn std::error::Error + Send + Sync>> {
let response = reqwest::Client::new() let response = reqwest::Client::new()
.get(link) .get(link)
.send() .send()
@@ -142,14 +98,12 @@ pub async fn download_file_by_link(
.error_for_status()?; .error_for_status()?;
if response.status() != StatusCode::OK { if response.status() != StatusCode::OK {
return Err(Box::new(DownloadError { return Ok(None);
status_code: response.status(),
}));
}; };
Ok(DownloadFile { Ok(Some(DownloadFile {
response, response,
filename, filename,
caption: "".to_string(), caption: "".to_string(),
}) }))
} }