From 35f707901f276ace2d4ea3fb2d31b1b8e28ea685 Mon Sep 17 00:00:00 2001 From: n08i40k Date: Sat, 6 Sep 2025 21:24:52 +0400 Subject: [PATCH] chore(clippy): fix all clippy warnings --- actix-macros/src/lib.rs | 6 +- database/src/query.rs | 1 + .../provider-engels-polytechnic/src/lib.rs | 4 +- .../src/parser/mod.rs | 104 ++++++++---------- .../src/updater.rs | 12 +- .../src/xls_downloader.rs | 6 +- src/extractors/authorized_user.rs | 1 - src/extractors/base.rs | 2 - src/middlewares/authorization.rs | 19 ++-- src/middlewares/content_type.rs | 23 ++-- src/routes/auth/shared.rs | 8 +- src/routes/auth/sign_in.rs | 4 +- src/routes/auth/sign_up.rs | 33 +++--- src/routes/flow/telegram_auth.rs | 3 +- src/routes/flow/telegram_complete.rs | 1 - src/routes/schedule/cache_status.rs | 10 +- src/routes/schedule/{schedule.rs => get.rs} | 0 src/routes/schedule/mod.rs | 4 +- src/routes/schedule/schema.rs | 12 -- src/routes/schema.rs | 18 +-- src/routes/users/change_group.rs | 1 - src/routes/users/change_username.rs | 1 - src/state/mod.rs | 8 +- src/utility/jwt.rs | 10 +- src/utility/telegram.rs | 2 +- 25 files changed, 126 insertions(+), 167 deletions(-) rename src/routes/schedule/{schedule.rs => get.rs} (100%) diff --git a/actix-macros/src/lib.rs b/actix-macros/src/lib.rs index 50a8c3b..da031a1 100644 --- a/actix-macros/src/lib.rs +++ b/actix-macros/src/lib.rs @@ -6,7 +6,7 @@ mod shared { use quote::{ToTokens, quote}; use syn::{Attribute, DeriveInput}; - pub fn find_status_code(attrs: &Vec) -> Option { + pub fn find_status_code(attrs: &[Attribute]) -> Option { attrs .iter() .find_map(|attr| -> Option { @@ -41,14 +41,12 @@ mod shared { let mut status_code_arms: Vec = variants .iter() - .map(|v| -> Option { + .filter_map(|v| -> Option { let status_code = find_status_code(&v.attrs)?; let variant_name = &v.ident; Some(quote! { #name::#variant_name => #status_code, }) }) - .filter(|v| v.is_some()) - .map(|v| v.unwrap()) .collect(); if status_code_arms.len() < variants.len() { diff --git a/database/src/query.rs b/database/src/query.rs index 746bf48..8712c9e 100644 --- a/database/src/query.rs +++ b/database/src/query.rs @@ -59,4 +59,5 @@ impl Query { define_is_exists!(user, id, str, Id); define_is_exists!(user, username, str, Username); define_is_exists!(user, telegram_id, i64, TelegramId); + define_is_exists!(user, vk_id, i32, VkId); } diff --git a/providers/provider-engels-polytechnic/src/lib.rs b/providers/provider-engels-polytechnic/src/lib.rs index f6e2a08..1f1a6cc 100644 --- a/providers/provider-engels-polytechnic/src/lib.rs +++ b/providers/provider-engels-polytechnic/src/lib.rs @@ -25,7 +25,7 @@ pub struct EngelsPolytechnicProvider { } impl EngelsPolytechnicProvider { - pub async fn new( + pub async fn get( update_source: UpdateSource, ) -> Result, crate::updater::error::Error> { let (updater, snapshot) = Updater::new(update_source).await?; @@ -60,7 +60,7 @@ impl ScheduleProvider for Wrapper { log::info!("Updating schedule..."); - match this.updater.update(&mut this.snapshot).await { + match this.updater.update(&this.snapshot).await { Ok(snapshot) => { this.snapshot = Arc::new(snapshot); }, diff --git a/providers/provider-engels-polytechnic/src/parser/mod.rs b/providers/provider-engels-polytechnic/src/parser/mod.rs index c9eb554..3c83656 100644 --- a/providers/provider-engels-polytechnic/src/parser/mod.rs +++ b/providers/provider-engels-polytechnic/src/parser/mod.rs @@ -1,5 +1,5 @@ use crate::or_continue; -use crate::parser::error::{ErrorCell, ErrorCellPos}; +use crate::parser::error::{Error, ErrorCell, ErrorCellPos}; use crate::parser::worksheet::WorkSheet; use crate::parser::LessonParseResult::{Lessons, Street}; use base::LessonType::Break; @@ -230,7 +230,7 @@ enum LessonParseResult { // noinspection GrazieInspection /// Obtaining a non-standard type of lesson by name. -fn guess_lesson_type(text: &String) -> Option { +fn guess_lesson_type(text: &str) -> Option { static MAP: LazyLock> = LazyLock::new(|| { HashMap::from([ ("консультация", LessonType::Consultation), @@ -245,22 +245,18 @@ fn guess_lesson_type(text: &String) -> Option { let name_lower = text.to_lowercase(); - match MAP - .iter() - .map(|(text, lesson_type)| (lesson_type, strsim::levenshtein(text, &*name_lower))) + MAP.iter() + .map(|(text, lesson_type)| (lesson_type, strsim::levenshtein(text, &name_lower))) .filter(|x| x.1 <= 4) .min_by_key(|(_, score)| *score) - { - None => None, - Some(v) => Some(v.0.clone()), - } + .map(|v| v.0.clone()) } /// Getting a pair or street from a cell. fn parse_lesson( worksheet: &WorkSheet, day: &Day, - day_boundaries: &Vec, + day_boundaries: &[BoundariesCellInfo], lesson_boundaries: &BoundariesCellInfo, group_column: u32, ) -> Result { @@ -297,7 +293,7 @@ fn parse_lesson( column: group_column, }))?; - let range: Option<[u8; 2]> = if lesson_boundaries.default_index != None { + let range: Option<[u8; 2]> = if lesson_boundaries.default_index.is_some() { let default = lesson_boundaries.default_index.unwrap() as u8; Some([default, end_time.default_index.unwrap() as u8]) } else { @@ -312,7 +308,11 @@ fn parse_lesson( Ok((range, time)) }?; - let (name, mut subgroups, lesson_type) = parse_name_and_subgroups(&name)?; + let ParsedLessonName { + name, + mut subgroups, + r#type: lesson_type, + } = parse_name_and_subgroups(&name)?; { let cabinets: Vec = parse_cabinets( @@ -325,12 +325,10 @@ fn parse_lesson( if cab_count == 1 { // Назначаем этот кабинет всем подгруппам - let cab = Some(cabinets.get(0).unwrap().clone()); + let cab = Some(cabinets.first().unwrap().clone()); - for subgroup in &mut subgroups { - if let Some(subgroup) = subgroup { - subgroup.cabinet = cab.clone() - } + for subgroup in subgroups.iter_mut().flatten() { + subgroup.cabinet = cab.clone() } } else if cab_count == 2 { while subgroups.len() < cab_count { @@ -361,10 +359,7 @@ fn parse_lesson( range: default_range, name: Some(name), time: lesson_time, - subgroups: if subgroups.len() == 2 - && subgroups.get(0).unwrap().is_none() - && subgroups.get(1).unwrap().is_none() - { + subgroups: if subgroups.len() == 2 && subgroups.iter().all(|x| x.is_none()) { None } else { Some(subgroups) @@ -416,12 +411,15 @@ fn parse_cabinets(worksheet: &WorkSheet, row_range: (u32, u32), column: u32) -> cabinets } +struct ParsedLessonName { + name: String, + subgroups: Vec>, + r#type: Option, +} + //noinspection GrazieInspection /// Getting the "pure" name of the lesson and list of teachers from the text of the lesson cell. -fn parse_name_and_subgroups( - text: &String, -) -> Result<(String, Vec>, Option), crate::parser::error::Error> -{ +fn parse_name_and_subgroups(text: &str) -> Result { // Части названия пары: // 1. Само название. // 2. Список преподавателей и подгрупп. @@ -458,7 +456,7 @@ fn parse_name_and_subgroups( static CLEAN_RE: LazyLock = LazyLock::new(|| Regex::new(r"[\s\n\t]+").unwrap()); let text = CLEAN_RE - .replace(&text.replace(&[' ', '\t', '\n'], " "), " ") + .replace(&text.replace([' ', '\t', '\n'], " "), " ") .to_string(); let (lesson_name, subgroups, lesson_type) = match NAMES_REGEX.captures(&text) { @@ -466,7 +464,7 @@ fn parse_name_and_subgroups( let capture = captures.get(0).unwrap(); let subgroups: Vec> = { - let src = capture.as_str().replace(&[' ', '.'], ""); + let src = capture.as_str().replace([' ', '.'], ""); let mut shared_subgroup = false; let mut subgroups: [Option; 2] = [None, None]; @@ -478,7 +476,7 @@ fn parse_name_and_subgroups( .map_or(0, |index| name[(index + 1)..(index + 2)].parse().unwrap()); let teacher_name = { - let name_end = open_bracket_index.unwrap_or_else(|| name.len()); + let name_end = open_bracket_index.unwrap_or(name.len()); // Я ебал. Как же я долго до этого доходил. format!( @@ -545,7 +543,11 @@ fn parse_name_and_subgroups( None => (text, Vec::new(), None), }; - Ok((lesson_name, subgroups, lesson_type)) + Ok(ParsedLessonName { + name: lesson_name, + subgroups, + r#type: lesson_type, + }) } /// Getting the start and end of a pair from a cell in the first column of a document. @@ -554,18 +556,11 @@ fn parse_name_and_subgroups( /// /// * `cell_data`: text in cell. /// * `date`: date of the current day. -fn parse_lesson_boundaries_cell( - cell_data: &String, - date: DateTime, -) -> Option { +fn parse_lesson_boundaries_cell(cell_data: &str, date: DateTime) -> Option { static TIME_RE: LazyLock = LazyLock::new(|| Regex::new(r"(\d+\.\d+)-(\d+\.\d+)").unwrap()); - let parse_res = if let Some(captures) = TIME_RE.captures(cell_data) { - captures - } else { - return None; - }; + let parse_res = TIME_RE.captures(cell_data)?; let start_match = parse_res.get(1).unwrap().as_str(); let start_parts: Vec<&str> = start_match.split(".").collect(); @@ -579,7 +574,7 @@ fn parse_lesson_boundaries_cell( }; Some(LessonBoundaries { - start: GET_TIME(date.clone(), &start_parts), + start: GET_TIME(date, &start_parts), end: GET_TIME(date, &end_parts), }) } @@ -607,7 +602,7 @@ fn parse_day_boundaries( continue; }; - let lesson_time = parse_lesson_boundaries_cell(&time_cell, date.clone()).ok_or( + let lesson_time = parse_lesson_boundaries_cell(&time_cell, date).ok_or( error::Error::LessonBoundaries(ErrorCell::new(row, column, time_cell.clone())), )?; @@ -652,7 +647,7 @@ fn parse_day_boundaries( /// * `week_markup`: markup of the current week. fn parse_week_boundaries( worksheet: &WorkSheet, - week_markup: &Vec, + week_markup: &[DayCellInfo], ) -> Result>, crate::parser::error::Error> { let mut result: Vec> = Vec::new(); @@ -671,8 +666,8 @@ fn parse_week_boundaries( }; let day_boundaries = parse_day_boundaries( - &worksheet, - day_markup.date.clone(), + worksheet, + day_markup.date, (day_markup.row, end_row), lesson_time_column, )?; @@ -698,7 +693,7 @@ fn convert_groups_to_teachers( .map(|day| Day { name: day.name.clone(), street: day.street.clone(), - date: day.date.clone(), + date: day.date, lessons: vec![], }) .collect(); @@ -774,19 +769,6 @@ fn convert_groups_to_teachers( /// * `buffer`: XLS data containing schedule. /// /// returns: Result -/// -/// # Examples -/// -/// ``` -/// use schedule_parser::parse_xls; -/// -/// let result = parse_xls(&include_bytes!("../../schedule.xls").to_vec()); -/// -/// assert!(result.is_ok(), "{}", result.err().unwrap()); -/// -/// assert_ne!(result.as_ref().unwrap().groups.len(), 0); -/// assert_ne!(result.as_ref().unwrap().teachers.len(), 0); -/// ``` pub fn parse_xls(buffer: &Vec) -> Result { let cursor = Cursor::new(&buffer); let mut workbook: Xls<_> = @@ -800,7 +782,7 @@ pub fn parse_xls(buffer: &Vec) -> Result) -> Result) -> Result day.lessons.append(lesson), diff --git a/providers/provider-engels-polytechnic/src/updater.rs b/providers/provider-engels-polytechnic/src/updater.rs index 3214974..bc50aa7 100644 --- a/providers/provider-engels-polytechnic/src/updater.rs +++ b/providers/provider-engels-polytechnic/src/updater.rs @@ -90,7 +90,7 @@ impl Updater { return Err(SnapshotCreationError::SameUrl); } - let head_result = downloader.set_url(&*url).await.map_err(|error| { + let head_result = downloader.set_url(&url).await.map_err(|error| { if let FetchError::Unknown(error) = &error { sentry::capture_error(&error); } @@ -152,10 +152,10 @@ impl Updater { .header("Authorization", format!("Api-Key {}", api_key)) .send() .await - .map_err(|error| QueryUrlError::RequestFailed(error))? + .map_err(QueryUrlError::RequestFailed)? .text() .await - .map_err(|error| QueryUrlError::RequestFailed(error))?; + .map_err(QueryUrlError::RequestFailed)?; Ok(format!("https://politehnikum-eng.ru{}", uri.trim())) } @@ -196,7 +196,7 @@ impl Updater { log::info!("Obtaining a link using FaaS..."); Self::query_url(yandex_api_key, yandex_func_id) .await - .map_err(|error| Error::QueryUrlFailed(error))? + .map_err(Error::QueryUrlFailed)? } _ => unreachable!(), }; @@ -205,7 +205,7 @@ impl Updater { let snapshot = Self::new_snapshot(&mut this.downloader, url) .await - .map_err(|error| Error::SnapshotCreationFailed(error))?; + .map_err(Error::SnapshotCreationFailed)?; log::info!("Schedule snapshot successfully created!"); @@ -243,7 +243,7 @@ impl Updater { yandex_func_id, } => Self::query_url(yandex_api_key.as_str(), yandex_func_id.as_str()) .await - .map_err(|error| Error::QueryUrlFailed(error))?, + .map_err(Error::QueryUrlFailed)?, _ => unreachable!(), }; diff --git a/providers/provider-engels-polytechnic/src/xls_downloader.rs b/providers/provider-engels-polytechnic/src/xls_downloader.rs index c5e465b..c188575 100644 --- a/providers/provider-engels-polytechnic/src/xls_downloader.rs +++ b/providers/provider-engels-polytechnic/src/xls_downloader.rs @@ -136,7 +136,7 @@ impl XlsDownloader { return Err(FetchError::bad_content_type(content_type.to_str().unwrap())); } - let last_modified = DateTime::parse_from_rfc2822(&last_modified.to_str().unwrap()) + let last_modified = DateTime::parse_from_rfc2822(last_modified.to_str().unwrap()) .unwrap() .with_timezone(&Utc); @@ -151,14 +151,14 @@ impl XlsDownloader { if self.url.is_none() { Err(FetchError::NoUrlProvided) } else { - Self::fetch_specified(&*self.url.as_ref().unwrap(), head).await + Self::fetch_specified(self.url.as_ref().unwrap(), head).await } } pub async fn set_url(&mut self, url: &str) -> FetchResult { let result = Self::fetch_specified(url, true).await; - if let Ok(_) = result { + if result.is_ok() { self.url = Some(url.to_string()); } diff --git a/src/extractors/authorized_user.rs b/src/extractors/authorized_user.rs index 7552641..4dc5433 100644 --- a/src/extractors/authorized_user.rs +++ b/src/extractors/authorized_user.rs @@ -11,7 +11,6 @@ use database::query::Query; use derive_more::Display; use serde::{Deserialize, Serialize}; use std::fmt::Debug; -use std::ops::Deref; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Display, MiddlewareError)] #[status_code = "actix_web::http::StatusCode::UNAUTHORIZED"] diff --git a/src/extractors/base.rs b/src/extractors/base.rs index 9207960..cf3a5e0 100644 --- a/src/extractors/base.rs +++ b/src/extractors/base.rs @@ -5,7 +5,6 @@ use std::future::{Ready, ready}; use std::ops; /// # Async extractor. - /// Asynchronous object extractor from a query. pub struct AsyncExtractor(T); @@ -80,7 +79,6 @@ impl FromRequest for AsyncExtractor { } /// # Sync extractor. - /// Synchronous object extractor from a query. pub struct SyncExtractor(T); diff --git a/src/middlewares/authorization.rs b/src/middlewares/authorization.rs index f293639..90835b1 100644 --- a/src/middlewares/authorization.rs +++ b/src/middlewares/authorization.rs @@ -1,25 +1,20 @@ use crate::extractors::authorized_user; use crate::extractors::base::FromRequestAsync; use actix_web::body::{BoxBody, EitherBody}; -use actix_web::dev::{Payload, Service, ServiceRequest, ServiceResponse, Transform, forward_ready}; +use actix_web::dev::{forward_ready, Payload, Service, ServiceRequest, ServiceResponse, Transform}; use actix_web::{Error, HttpRequest, ResponseError}; -use futures_util::future::LocalBoxFuture; -use std::future::{Ready, ready}; -use std::rc::Rc; use database::entity::User; +use futures_util::future::LocalBoxFuture; +use std::future::{ready, Ready}; +use std::rc::Rc; /// Middleware guard working with JWT tokens. +#[derive(Default)] pub struct JWTAuthorization { /// List of ignored endpoints. pub ignore: &'static [&'static str], } -impl Default for JWTAuthorization { - fn default() -> Self { - Self { ignore: &[] } - } -} - impl Transform for JWTAuthorization where S: Service, Error = Error> + 'static, @@ -70,8 +65,8 @@ where return false; } - if let Some(other) = path.as_bytes().iter().nth(ignore.len()) { - return ['?' as u8, '/' as u8].contains(other); + if let Some(other) = path.as_bytes().get(ignore.len()) { + return [b'?', b'/'].contains(other); } true diff --git a/src/middlewares/content_type.rs b/src/middlewares/content_type.rs index 50ee2b4..e657216 100644 --- a/src/middlewares/content_type.rs +++ b/src/middlewares/content_type.rs @@ -1,10 +1,10 @@ -use actix_web::Error; use actix_web::body::{BoxBody, EitherBody}; -use actix_web::dev::{Service, ServiceRequest, ServiceResponse, Transform, forward_ready}; +use actix_web::dev::{forward_ready, Service, ServiceRequest, ServiceResponse, Transform}; use actix_web::http::header; use actix_web::http::header::HeaderValue; +use actix_web::Error; use futures_util::future::LocalBoxFuture; -use std::future::{Ready, ready}; +use std::future::{ready, Ready}; /// Middleware to specify the encoding in the Content-Type header. pub struct ContentTypeBootstrap; @@ -30,7 +30,7 @@ pub struct ContentTypeMiddleware { service: S, } -impl<'a, S, B> Service for ContentTypeMiddleware +impl Service for ContentTypeMiddleware where S: Service, Error = Error>, S::Future: 'static, @@ -49,13 +49,14 @@ where let mut response = fut.await?; let headers = response.response_mut().headers_mut(); - if let Some(content_type) = headers.get("Content-Type") { - if content_type == "application/json" { - headers.insert( - header::CONTENT_TYPE, - HeaderValue::from_static("application/json; charset=utf8"), - ); - } + + if let Some(content_type) = headers.get("Content-Type") + && content_type == "application/json" + { + headers.insert( + header::CONTENT_TYPE, + HeaderValue::from_static("application/json; charset=utf8"), + ); } Ok(response.map_into_left_body()) diff --git a/src/routes/auth/shared.rs b/src/routes/auth/shared.rs index 4341dcd..b5ee062 100644 --- a/src/routes/auth/shared.rs +++ b/src/routes/auth/shared.rs @@ -22,7 +22,7 @@ struct Claims { #[derive(Debug, PartialEq)] pub enum Error { - JwtError(ErrorKind), + Jwt(ErrorKind), InvalidSignature, InvalidToken, Expired, @@ -49,10 +49,10 @@ const VK_PUBLIC_KEY: &str = concat!( "-----END PUBLIC KEY-----" ); -pub fn parse_vk_id(token_str: &String, client_id: i32) -> Result { +pub fn parse_vk_id(token_str: &str, client_id: i32) -> Result { let dkey = DecodingKey::from_rsa_pem(VK_PUBLIC_KEY.as_bytes()).unwrap(); - match decode::(&token_str, &dkey, &Validation::new(Algorithm::RS256)) { + match decode::(token_str, &dkey, &Validation::new(Algorithm::RS256)) { Ok(token_data) => { let claims = token_data.claims; @@ -77,7 +77,7 @@ pub fn parse_vk_id(token_str: &String, client_id: i32) -> Result { ErrorKind::Base64(_) => Error::InvalidToken, ErrorKind::Json(_) => Error::InvalidToken, ErrorKind::Utf8(_) => Error::InvalidToken, - kind => Error::JwtError(kind), + kind => Error::Jwt(kind), }), } } diff --git a/src/routes/auth/sign_in.rs b/src/routes/auth/sign_in.rs index de74171..f8d0f6b 100644 --- a/src/routes/auth/sign_in.rs +++ b/src/routes/auth/sign_in.rs @@ -28,7 +28,7 @@ async fn sign_in_combined( return Err(ErrorCode::IncorrectCredentials); } - match bcrypt::verify(&data.password, &user.password.as_ref().unwrap()) { + match bcrypt::verify(&data.password, user.password.as_ref().unwrap()) { Ok(result) => { if !result { return Err(ErrorCode::IncorrectCredentials); @@ -124,8 +124,6 @@ mod schema { InvalidVkAccessToken, } - /// Internal - /// Type of authorization. pub enum SignInData { /// User and password name and password. diff --git a/src/routes/auth/sign_up.rs b/src/routes/auth/sign_up.rs index 66730b5..82a8274 100644 --- a/src/routes/auth/sign_up.rs +++ b/src/routes/auth/sign_up.rs @@ -8,7 +8,6 @@ use database::entity::sea_orm_active_enums::UserRole; use database::entity::ActiveUser; use database::query::Query; use database::sea_orm::ActiveModelTrait; -use std::ops::Deref; use web::Json; async fn sign_up_combined( @@ -42,13 +41,12 @@ async fn sign_up_combined( } // If user with specified VKID already exists. - if let Some(id) = data.vk_id { - if Query::find_user_by_vk_id(db, id) + if let Some(id) = data.vk_id + && Query::is_user_exists_by_vk_id(db, id) .await - .is_ok_and(|user| user.is_some()) - { - return Err(ErrorCode::VkAlreadyExists); - } + .expect("Failed to check user existence") + { + return Err(ErrorCode::VkAlreadyExists); } let active_user: ActiveUser = data.into(); @@ -202,8 +200,6 @@ mod schema { VkAlreadyExists, } - /// Internal - /// Data for registration. pub struct SignUpData { // TODO: сделать ограничение на минимальную и максимальную длину при регистрации и смене. @@ -228,21 +224,21 @@ mod schema { pub version: String, } - impl Into for SignUpData { - fn into(self) -> ActiveUser { - assert_ne!(self.password.is_some(), self.vk_id.is_some()); + impl From for ActiveUser { + fn from(value: SignUpData) -> Self { + assert_ne!(value.password.is_some(), value.vk_id.is_some()); ActiveUser { id: Set(ObjectId::new().unwrap().to_string()), - username: Set(self.username), - password: Set(self + username: Set(value.username), + password: Set(value .password .map(|x| bcrypt::hash(x, bcrypt::DEFAULT_COST).unwrap())), - vk_id: Set(self.vk_id), + vk_id: Set(value.vk_id), telegram_id: Set(None), - group: Set(Some(self.group)), - role: Set(self.role), - android_version: Set(Some(self.version)), + group: Set(Some(value.group)), + role: Set(value.role), + android_version: Set(Some(value.version)), } } } @@ -262,7 +258,6 @@ mod tests { use database::entity::{UserColumn, UserEntity}; use database::sea_orm::ColumnTrait; use database::sea_orm::{EntityTrait, QueryFilter}; - use std::ops::Deref; struct SignUpPartial<'a> { username: &'a str, diff --git a/src/routes/flow/telegram_auth.rs b/src/routes/flow/telegram_auth.rs index e132445..9f3c804 100644 --- a/src/routes/flow/telegram_auth.rs +++ b/src/routes/flow/telegram_auth.rs @@ -9,7 +9,6 @@ use database::entity::ActiveUser; use database::query::Query; use database::sea_orm::{ActiveModelTrait, Set}; use objectid::ObjectId; -use std::ops::Deref; use std::sync::Arc; use web::Json; @@ -122,7 +121,7 @@ mod schema { &mut self, request: &HttpRequest, response: &mut HttpResponse>, - ) -> () { + ) { let access_token = &self.access_token; let app_state = request.app_data::>().unwrap(); diff --git a/src/routes/flow/telegram_complete.rs b/src/routes/flow/telegram_complete.rs index 64c6f6f..d77e52a 100644 --- a/src/routes/flow/telegram_complete.rs +++ b/src/routes/flow/telegram_complete.rs @@ -6,7 +6,6 @@ use actix_web::{post, web}; use database::entity::User; use database::query::Query; use database::sea_orm::{ActiveModelTrait, IntoActiveModel, Set}; -use std::ops::Deref; use web::Json; #[utoipa::path(responses( diff --git a/src/routes/schedule/cache_status.rs b/src/routes/schedule/cache_status.rs index ed18854..e4d48e1 100644 --- a/src/routes/schedule/cache_status.rs +++ b/src/routes/schedule/cache_status.rs @@ -1,11 +1,17 @@ -use crate::AppState; use crate::routes::schedule::schema::CacheStatus; +use crate::AppState; use actix_web::{get, web}; +use std::ops::Deref; #[utoipa::path(responses( (status = OK, body = CacheStatus), ))] #[get("/cache-status")] pub async fn cache_status(app_state: web::Data) -> CacheStatus { - CacheStatus::from(&app_state).await.into() + app_state + .get_schedule_snapshot("eng_polytechnic") + .await + .unwrap() + .deref() + .into() } diff --git a/src/routes/schedule/schedule.rs b/src/routes/schedule/get.rs similarity index 100% rename from src/routes/schedule/schedule.rs rename to src/routes/schedule/get.rs diff --git a/src/routes/schedule/mod.rs b/src/routes/schedule/mod.rs index cd7d11c..704750f 100644 --- a/src/routes/schedule/mod.rs +++ b/src/routes/schedule/mod.rs @@ -1,7 +1,7 @@ mod cache_status; mod group; mod group_names; -mod schedule; +mod get; mod schema; mod teacher; mod teacher_names; @@ -9,6 +9,6 @@ mod teacher_names; pub use cache_status::*; pub use group::*; pub use group_names::*; -pub use schedule::*; +pub use get::*; pub use teacher::*; pub use teacher_names::*; diff --git a/src/routes/schedule/schema.rs b/src/routes/schedule/schema.rs index 6aa5219..6fc968e 100644 --- a/src/routes/schedule/schema.rs +++ b/src/routes/schedule/schema.rs @@ -63,18 +63,6 @@ pub struct CacheStatus { pub updated_at: i64, } -impl CacheStatus { - pub async fn from(value: &web::Data) -> Self { - From::<&ScheduleSnapshot>::from( - value - .get_schedule_snapshot("eng_polytechnic") - .await - .unwrap() - .deref(), - ) - } -} - impl From<&ScheduleSnapshot> for CacheStatus { fn from(value: &ScheduleSnapshot) -> Self { Self { diff --git a/src/routes/schema.rs b/src/routes/schema.rs index b9b6e79..bd01117 100644 --- a/src/routes/schema.rs +++ b/src/routes/schema.rs @@ -13,13 +13,13 @@ where E: Serialize + PartialSchema + Display + PartialErrResponse; /// Transform Response into Result -impl Into> for Response +impl From> for Result where T: Serialize + PartialSchema + PartialOkResponse, E: Serialize + PartialSchema + Display + PartialErrResponse, { - fn into(self) -> Result { - self.0 + fn from(value: Response) -> Self { + value.0 } } @@ -46,7 +46,7 @@ where { match &self.0 { Ok(ok) => serializer.serialize_some(&ok), - Err(err) => serializer.serialize_some(&ResponseError::::from(err.clone().into())), + Err(err) => serializer.serialize_some(&err.clone().into()), } } } @@ -95,7 +95,7 @@ pub trait PartialOkResponse { &mut self, _request: &HttpRequest, _response: &mut HttpResponse>, - ) -> () { + ) { } } @@ -173,8 +173,8 @@ pub mod user { username: user.username.clone(), group: user.group.clone(), role: user.role.clone(), - vk_id: user.vk_id.clone(), - telegram_id: user.telegram_id.clone(), + vk_id: user.vk_id, + telegram_id: user.telegram_id, access_token: Some(access_token), } } @@ -188,8 +188,8 @@ pub mod user { username: user.username.clone(), group: user.group.clone(), role: user.role.clone(), - vk_id: user.vk_id.clone(), - telegram_id: user.telegram_id.clone(), + vk_id: user.vk_id, + telegram_id: user.telegram_id, access_token: None, } } diff --git a/src/routes/users/change_group.rs b/src/routes/users/change_group.rs index 0913f19..8ee038c 100644 --- a/src/routes/users/change_group.rs +++ b/src/routes/users/change_group.rs @@ -4,7 +4,6 @@ use crate::state::AppState; use actix_web::{post, web}; use database::entity::User; use database::sea_orm::{ActiveModelTrait, IntoActiveModel, Set}; -use std::ops::Deref; #[utoipa::path(responses((status = OK)))] #[post("/change-group")] diff --git a/src/routes/users/change_username.rs b/src/routes/users/change_username.rs index 4c942d5..187b124 100644 --- a/src/routes/users/change_username.rs +++ b/src/routes/users/change_username.rs @@ -5,7 +5,6 @@ use actix_web::{post, web}; use database::entity::User; use database::query::Query; use database::sea_orm::{ActiveModelTrait, IntoActiveModel, Set}; -use std::ops::Deref; #[utoipa::path(responses((status = OK)))] #[post("/change-username")] diff --git a/src/state/mod.rs b/src/state/mod.rs index d29883e..9e9e064 100644 --- a/src/state/mod.rs +++ b/src/state/mod.rs @@ -23,7 +23,7 @@ impl AppState { let env = AppEnv::default(); let providers: HashMap> = HashMap::from([( "eng_polytechnic".to_string(), - providers::EngelsPolytechnicProvider::new({ + providers::EngelsPolytechnicProvider::get({ #[cfg(test)] { providers::EngelsPolytechnicUpdateSource::Prepared(ScheduleSnapshot { @@ -64,7 +64,7 @@ impl AppState { }; if this.env.schedule.auto_update { - for (_, provider) in &this.providers { + for provider in this.providers.values() { let provider = provider.clone(); let cancel_token = this.cancel_token.clone(); @@ -93,6 +93,8 @@ impl AppState { } /// Create a new object web::Data. -pub async fn new_app_state(database: Option) -> Result, Box> { +pub async fn new_app_state( + database: Option, +) -> Result, Box> { Ok(web::Data::new(AppState::new(database).await?)) } diff --git a/src/utility/jwt.rs b/src/utility/jwt.rs index bd82254..511b687 100644 --- a/src/utility/jwt.rs +++ b/src/utility/jwt.rs @@ -63,13 +63,13 @@ struct Claims { pub(crate) const DEFAULT_ALGORITHM: Algorithm = Algorithm::HS256; /// Checking the token and extracting the UUID of the user account from it. -pub fn verify_and_decode(token: &String) -> Result { +pub fn verify_and_decode(token: &str) -> Result { let mut validation = Validation::new(DEFAULT_ALGORITHM); validation.required_spec_claims.remove("exp"); validation.validate_exp = false; - let result = decode::(&token, &*DECODING_KEY, &validation); + let result = decode::(token, &DECODING_KEY, &validation); match result { Ok(token_data) => { @@ -88,7 +88,7 @@ pub fn verify_and_decode(token: &String) -> Result { } /// Creating a user token. -pub fn encode(id: &String) -> String { +pub fn encode(id: &str) -> String { let header = Header { typ: Some(String::from("JWT")), ..Default::default() @@ -98,12 +98,12 @@ pub fn encode(id: &String) -> String { let exp = iat + Duration::days(365 * 4); let claims = Claims { - id: id.clone(), + id: id.to_string(), iat: iat.timestamp().unsigned_abs(), exp: exp.timestamp().unsigned_abs(), }; - jsonwebtoken::encode(&header, &claims, &*ENCODING_KEY).unwrap() + jsonwebtoken::encode(&header, &claims, &ENCODING_KEY).unwrap() } #[cfg(test)] diff --git a/src/utility/telegram.rs b/src/utility/telegram.rs index 3e9fa03..a4a421a 100644 --- a/src/utility/telegram.rs +++ b/src/utility/telegram.rs @@ -33,7 +33,7 @@ impl WebAppInitDataMap { }; data.split('&') - .map(|kv| kv.split_once('=').unwrap_or_else(|| (kv, ""))) + .map(|kv| kv.split_once('=').unwrap_or((kv, ""))) .for_each(|(key, value)| { this.data_map.insert(key.to_string(), value.to_string()); });