Update
Some checks failed
Build docker image / Build-Docker-Image (push) Has been cancelled

This commit is contained in:
2025-01-04 16:15:12 +01:00
parent bdea8e7de3
commit e2e4088a6f
17 changed files with 95 additions and 115 deletions

View File

@@ -53,7 +53,9 @@ impl Display for DownloadArchiveQueryData {
DownloadArchiveQueryData::Sequence { id, file_type } => { DownloadArchiveQueryData::Sequence { id, file_type } => {
write!(f, "da_s_{}_{}", id, file_type) write!(f, "da_s_{}_{}", id, file_type)
} }
DownloadArchiveQueryData::Author { id, file_type } => write!(f, "da_a_{}_{}", id, file_type), DownloadArchiveQueryData::Author { id, file_type } => {
write!(f, "da_a_{}_{}", id, file_type)
}
DownloadArchiveQueryData::Translator { id, file_type } => { DownloadArchiveQueryData::Translator { id, file_type } => {
write!(f, "da_t_{}_{}", id, file_type) write!(f, "da_t_{}_{}", id, file_type)
} }

View File

@@ -22,7 +22,9 @@ use crate::{
approved_bot::{ approved_bot::{
modules::download::callback_data::DownloadArchiveQueryData, modules::download::callback_data::DownloadArchiveQueryData,
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, download_file, download_file_by_link, get_cached_message,
types::{CachedMessage, DownloadFile}, types::{CachedMessage, DownloadFile},
@@ -38,7 +40,8 @@ use crate::{
}, },
BotHandlerInternal, BotHandlerInternal,
}, },
bots_manager::BotCache, config, bots_manager::BotCache,
config,
}; };
use self::{ use self::{
@@ -133,10 +136,12 @@ async fn _send_downloaded_file(
let document: InputFile = InputFile::read(data).file_name(filename.clone()); let document: InputFile = InputFile::read(data).file_name(filename.clone());
match bot.send_document(message.chat().id, document) match bot
.send_document(message.chat().id, document)
.caption(caption) .caption(caption)
.send() .send()
.await { .await
{
Ok(_) => (), Ok(_) => (),
Err(err) => { Err(err) => {
log::error!("Download error: {:?} | {:?}", filename, err); log::error!("Download error: {:?} | {:?}", filename, err);
@@ -152,7 +157,6 @@ async fn _send_downloaded_file(
Ok(()) Ok(())
} }
async fn send_with_download_from_channel( async fn send_with_download_from_channel(
message: MaybeInaccessibleMessage, message: MaybeInaccessibleMessage,
bot: CacheMe<Throttle<Bot>>, bot: CacheMe<Throttle<Bot>>,
@@ -165,7 +169,7 @@ async fn send_with_download_from_channel(
Some(v) => v, Some(v) => v,
None => { None => {
return Ok(()); return Ok(());
}, }
}; };
_send_downloaded_file(&message, bot.clone(), download_file).await?; _send_downloaded_file(&message, bot.clone(), download_file).await?;
@@ -182,7 +186,6 @@ async fn send_with_download_from_channel(
} }
} }
async fn download_handler( async fn download_handler(
message: MaybeInaccessibleMessage, message: MaybeInaccessibleMessage,
bot: CacheMe<Throttle<Bot>>, bot: CacheMe<Throttle<Bot>>,
@@ -412,18 +415,14 @@ async fn wait_archive(
task.id task.id
); );
let downloaded_data = match download_file_by_link( let downloaded_data =
task.clone().result_filename.unwrap(), match download_file_by_link(task.clone().result_filename.unwrap(), link).await {
link,
)
.await
{
Ok(v) => match v { Ok(v) => match v {
Some(v) => v, Some(v) => v,
None => { None => {
send_error_message(bot, message.chat.id, message.id).await; send_error_message(bot, message.chat.id, message.id).await;
return Ok(()); 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;
@@ -432,7 +431,13 @@ async fn wait_archive(
} }
}; };
match _send_downloaded_file(&MaybeInaccessibleMessage::Regular(message.clone()), bot.clone(), downloaded_data).await { match _send_downloaded_file(
&MaybeInaccessibleMessage::Regular(message.clone()),
bot.clone(),
downloaded_data,
)
.await
{
Ok(_) => (), Ok(_) => (),
Err(err) => { Err(err) => {
send_archive_link(bot.clone(), message.clone(), task).await?; send_archive_link(bot.clone(), message.clone(), task).await?;

View File

@@ -47,7 +47,7 @@ pub fn get_help_handler() -> crate::bots::BotHandler {
Update::filter_message().branch( Update::filter_message().branch(
dptree::entry() dptree::entry()
.filter_command::<HelpCommand>() .filter_command::<HelpCommand>()
.endpoint(|message, bot| async move { help_handler(message, bot).await }), .endpoint(help_handler),
), ),
) )
} }

View File

@@ -1,24 +1,16 @@
use teloxide::types::{CallbackQuery, MaybeInaccessibleMessage}; use teloxide::types::{CallbackQuery, MaybeInaccessibleMessage};
pub fn get_query(cq: CallbackQuery) -> Option<String> { pub fn get_query(cq: CallbackQuery) -> Option<String> {
match cq.message { match cq.message {
Some(message) => { Some(message) => match message {
match message { MaybeInaccessibleMessage::Regular(message) => match message.reply_to_message() {
MaybeInaccessibleMessage::Regular(message) => { Some(reply_to_message) => reply_to_message
match message.reply_to_message() {
Some(reply_to_message) => {
reply_to_message
.text() .text()
.map(|text| text.replace(['/', '&', '?'], "")) .map(|text| text.replace(['/', '&', '?'], "")),
}
None => None, None => None,
} },
}
MaybeInaccessibleMessage::Inaccessible(_) => None, MaybeInaccessibleMessage::Inaccessible(_) => None,
} },
}
None => None, None => None,
} }
} }

View File

@@ -158,19 +158,12 @@ pub fn get_settings_handler() -> crate::bots::BotHandler {
Update::filter_message().branch( Update::filter_message().branch(
dptree::entry() dptree::entry()
.filter_command::<SettingsCommand>() .filter_command::<SettingsCommand>()
.endpoint(|message, bot| async move { settings_handler(message, bot).await }), .endpoint(settings_handler),
), ),
) )
.branch( .branch(
Update::filter_callback_query() Update::filter_callback_query()
.chain(filter_callback_query::<SettingsCallbackData>()) .chain(filter_callback_query::<SettingsCallbackData>())
.endpoint( .endpoint(settings_callback_handler),
|cq: CallbackQuery,
bot: CacheMe<Throttle<Bot>>,
callback_data: SettingsCallbackData,
me: Me| async move {
settings_callback_handler(cq, bot, callback_data, me).await
},
),
) )
} }

View File

@@ -1,7 +1,9 @@
use crate::bots::BotHandlerInternal; use crate::bots::BotHandlerInternal;
use teloxide::{ use teloxide::{
adaptors::{CacheMe, Throttle}, prelude::*, utils::command::BotCommands adaptors::{CacheMe, Throttle},
prelude::*,
utils::command::BotCommands,
}; };
#[derive(BotCommands, Clone)] #[derive(BotCommands, Clone)]
@@ -16,8 +18,7 @@ pub async fn support_command_handler(
bot: CacheMe<Throttle<Bot>>, bot: CacheMe<Throttle<Bot>>,
) -> BotHandlerInternal { ) -> BotHandlerInternal {
let username = match message.clone().from { let username = match message.clone().from {
Some(user) => { Some(user) => match user.is_bot {
match user.is_bot {
true => match message.reply_to_message() { true => match message.reply_to_message() {
Some(v) => match &v.from { Some(v) => match &v.from {
Some(v) => v.first_name.clone(), Some(v) => v.first_name.clone(),
@@ -26,8 +27,7 @@ pub async fn support_command_handler(
None => "пользователь".to_string(), None => "пользователь".to_string(),
}, },
false => user.first_name, false => user.first_name,
} },
}
None => "пользователь".to_string(), None => "пользователь".to_string(),
}; };

View File

@@ -154,20 +154,14 @@ pub fn get_update_log_handler() -> crate::bots::BotHandler {
Update::filter_message().branch( Update::filter_message().branch(
dptree::entry() dptree::entry()
.filter_command::<UpdateLogCommand>() .filter_command::<UpdateLogCommand>()
.endpoint(|message, bot| async move { update_log_command(message, bot).await }), .endpoint(update_log_command),
), ),
) )
.branch( .branch(
Update::filter_callback_query().branch( Update::filter_callback_query().branch(
dptree::entry() dptree::entry()
.chain(filter_callback_query::<UpdateLogCallbackData>()) .chain(filter_callback_query::<UpdateLogCallbackData>())
.endpoint( .endpoint(update_log_pagination_handler),
|cq: CallbackQuery,
bot: CacheMe<Throttle<Bot>>,
update_log_data: UpdateLogCallbackData| async move {
update_log_pagination_handler(cq, bot, update_log_data).await
},
),
), ),
) )
} }

View File

@@ -6,10 +6,8 @@ use serde::{Deserialize, Serialize};
use crate::config; use crate::config;
pub static CLIENT: Lazy<reqwest::Client> = Lazy::new(reqwest::Client::new); pub static CLIENT: Lazy<reqwest::Client> = Lazy::new(reqwest::Client::new);
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
#[serde(rename_all = "snake_case")] #[serde(rename_all = "snake_case")]
pub enum TaskObjectType { pub enum TaskObjectType {

View File

@@ -2,16 +2,17 @@ use base64::{engine::general_purpose, Engine};
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use reqwest::StatusCode; use reqwest::StatusCode;
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}; use self::types::{CachedMessage, DownloadFile};
pub mod types; pub mod types;
pub static CLIENT: Lazy<reqwest::Client> = Lazy::new(reqwest::Client::new); pub static CLIENT: Lazy<reqwest::Client> = Lazy::new(reqwest::Client::new);
pub async fn get_cached_message( pub async fn get_cached_message(
download_data: &DownloadQueryData, download_data: &DownloadQueryData,
bot_cache: BotCache, bot_cache: BotCache,
@@ -40,7 +41,6 @@ pub async fn get_cached_message(
Ok(Some(response.json::<CachedMessage>().await?)) Ok(Some(response.json::<CachedMessage>().await?))
} }
pub async fn download_file( pub async fn download_file(
download_data: &DownloadQueryData, download_data: &DownloadQueryData,
) -> Result<Option<DownloadFile>, Box<dyn std::error::Error + Send + Sync>> { ) -> Result<Option<DownloadFile>, Box<dyn std::error::Error + Send + Sync>> {
@@ -90,15 +90,11 @@ pub async fn download_file(
})) }))
} }
pub async fn download_file_by_link( pub async fn download_file_by_link(
filename: String, filename: String,
link: String, link: String,
) -> Result<Option<DownloadFile>, Box<dyn std::error::Error + Send + Sync>> { ) -> Result<Option<DownloadFile>, Box<dyn std::error::Error + Send + Sync>> {
let response = CLIENT let response = CLIENT.get(link).send().await?;
.get(link)
.send()
.await?;
if response.status() != StatusCode::OK { if response.status() != StatusCode::OK {
return Ok(None); return Ok(None);

View File

@@ -12,10 +12,8 @@ use crate::config;
use self::types::Empty; use self::types::Empty;
pub static CLIENT: Lazy<reqwest::Client> = Lazy::new(reqwest::Client::new); pub static CLIENT: Lazy<reqwest::Client> = Lazy::new(reqwest::Client::new);
fn get_allowed_langs_params( fn get_allowed_langs_params(
allowed_langs: SmallVec<[SmartString; 3]>, allowed_langs: SmallVec<[SmartString; 3]>,
) -> Vec<(&'static str, SmartString)> { ) -> Vec<(&'static str, SmartString)> {

View File

@@ -205,7 +205,7 @@ pub struct Book {
// id_deleted: bool, // id_deleted: bool,
pub year: i32, pub year: i32,
pub pages: Option<u32>, pub pages: Option<u32>,
pub position: Option<i32> pub position: Option<i32>,
} }
#[derive(Deserialize, Debug, Clone)] #[derive(Deserialize, Debug, Clone)]
@@ -237,7 +237,7 @@ impl From<SearchBook> for Book {
genres: vec![], genres: vec![],
pages: None, pages: None,
year: value.year, year: value.year,
position: None position: None,
} }
} }
} }
@@ -270,7 +270,7 @@ impl From<AuthorBook> for Book {
genres: vec![], genres: vec![],
pages: None, pages: None,
year: value.year, year: value.year,
position: None position: None,
} }
} }
} }
@@ -303,7 +303,7 @@ impl From<TranslatorBook> for Book {
genres: vec![], genres: vec![],
pages: None, pages: None,
year: value.year, year: value.year,
position: None position: None,
} }
} }
} }
@@ -320,7 +320,7 @@ pub struct SequenceBook {
pub translators: Vec<BookTranslator>, pub translators: Vec<BookTranslator>,
pub annotation_exists: bool, pub annotation_exists: bool,
pub year: i32, pub year: i32,
pub position: i32 pub position: i32,
} }
impl From<SequenceBook> for Book { impl From<SequenceBook> for Book {
@@ -337,7 +337,7 @@ impl From<SequenceBook> for Book {
genres: vec![], genres: vec![],
pages: None, pages: None,
year: value.year, year: value.year,
position: Some(value.position) position: Some(value.position),
} }
} }
} }

View File

@@ -1,5 +1,7 @@
use teloxide::{ use teloxide::{
adaptors::{CacheMe, Throttle}, types::MaybeInaccessibleMessage, Bot adaptors::{CacheMe, Throttle},
types::MaybeInaccessibleMessage,
Bot,
}; };
use crate::{ use crate::{

View File

@@ -9,10 +9,8 @@ use tracing::log;
use crate::{bots_manager::USER_LANGS_CACHE, config}; use crate::{bots_manager::USER_LANGS_CACHE, config};
pub static CLIENT: Lazy<reqwest::Client> = Lazy::new(reqwest::Client::new); pub static CLIENT: Lazy<reqwest::Client> = Lazy::new(reqwest::Client::new);
#[derive(Deserialize, Debug, Clone)] #[derive(Deserialize, Debug, Clone)]
pub struct Lang { pub struct Lang {
// pub id: u32, // pub id: u32,
@@ -70,7 +68,7 @@ pub async fn get_user_or_default_lang_codes(user_id: UserId) -> SmallVec<[SmartS
Err(err) => { Err(err) => {
log::error!("{:?}", err); log::error!("{:?}", err);
default_lang_codes default_lang_codes
}, }
} }
} }

View File

@@ -1,6 +1,7 @@
use teloxide::{ use teloxide::{
adaptors::{CacheMe, Throttle}, adaptors::{CacheMe, Throttle},
prelude::*, types::ReplyParameters, prelude::*,
types::ReplyParameters,
}; };
use std::error::Error; use std::error::Error;
@@ -11,7 +12,6 @@ pub mod register;
pub mod strings; pub mod strings;
pub mod utils; pub mod utils;
pub async fn message_handler( pub async fn message_handler(
message: Message, message: Message,
bot: CacheMe<Throttle<Bot>>, bot: CacheMe<Throttle<Bot>>,

View File

@@ -3,10 +3,8 @@ use serde::Deserialize;
use crate::config; use crate::config;
pub static CLIENT: Lazy<reqwest::Client> = Lazy::new(reqwest::Client::new); pub static CLIENT: Lazy<reqwest::Client> = Lazy::new(reqwest::Client::new);
#[derive(Deserialize, Debug, PartialEq, Clone, Copy)] #[derive(Deserialize, Debug, PartialEq, Clone, Copy)]
pub enum BotCache { pub enum BotCache {
#[serde(rename = "original")] #[serde(rename = "original")]
@@ -37,7 +35,6 @@ pub async fn get_bots() -> Result<Vec<BotData>, reqwest::Error> {
} }
} }
pub async fn delete_bot(id: u32) -> Result<(), reqwest::Error> { pub async fn delete_bot(id: u32) -> Result<(), reqwest::Error> {
let response = CLIENT let response = CLIENT
.delete(format!("{}/{}/", config::CONFIG.manager_url, id)) .delete(format!("{}/{}/", config::CONFIG.manager_url, id))

View File

@@ -15,8 +15,8 @@ use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc; use std::sync::Arc;
use smallvec::SmallVec; use smallvec::SmallVec;
use tokio::time::{sleep, Duration};
use tokio::sync::Semaphore; use tokio::sync::Semaphore;
use tokio::time::{sleep, Duration};
use teloxide::prelude::*; use teloxide::prelude::*;
@@ -137,7 +137,10 @@ impl BotsManager {
pub async fn check_pending_updates() { pub async fn check_pending_updates() {
for (token, bot_data) in BOTS_DATA.iter() { for (token, bot_data) in BOTS_DATA.iter() {
let error_count = WEBHOOK_CHECK_ERRORS_COUNT.get(&bot_data.id).await.unwrap_or(0); let error_count = WEBHOOK_CHECK_ERRORS_COUNT
.get(&bot_data.id)
.await
.unwrap_or(0);
if error_count >= 3 { if error_count >= 3 {
continue; continue;
@@ -154,19 +157,18 @@ impl BotsManager {
} }
if webhook_info.last_error_message.is_some() { if webhook_info.last_error_message.is_some() {
log::error!( log::error!("Webhook last error: {:?}", webhook_info.last_error_message);
"Webhook last error: {:?}",
webhook_info.last_error_message
);
set_webhook(&bot_data).await; set_webhook(&bot_data).await;
} }
}, }
Err(err) => { Err(err) => {
log::error!("Error getting webhook info: {:?}", err); log::error!("Error getting webhook info: {:?}", err);
WEBHOOK_CHECK_ERRORS_COUNT.insert(bot_data.id, error_count + 1).await; WEBHOOK_CHECK_ERRORS_COUNT
}, .insert(bot_data.id, error_count + 1)
.await;
}
} }
} }
} }

View File

@@ -26,7 +26,10 @@ async fn main() {
let _guard = sentry::init(options); let _guard = sentry::init(options);
let sentry_layer = sentry_tracing::layer().event_filter(|md| { let sentry_layer = sentry_tracing::layer().event_filter(|md| {
if md.name().contains("Forbidden: bot can't initiate conversation with a user") { if md
.name()
.contains("Forbidden: bot can't initiate conversation with a user")
{
return EventFilter::Ignore; return EventFilter::Ignore;
} }