Обновление документации.

This commit is contained in:
2025-04-15 22:09:10 +04:00
parent 2fd6d787a0
commit 5068fe3069
26 changed files with 370 additions and 235 deletions

View File

@@ -86,11 +86,11 @@ mod schema {
#[derive(Deserialize, Serialize, ToSchema)]
#[schema(as = SignIn::Request)]
pub struct Request {
/// Имя пользователя
/// User name.
#[schema(examples("n08i40k"))]
pub username: String,
/// Пароль
/// Password.
pub password: String,
}
@@ -102,7 +102,7 @@ mod schema {
#[serde(rename_all = "camelCase")]
#[schema(as = SignInVk::Request)]
pub struct Request {
/// Токен VK ID
/// VK ID token.
pub access_token: String,
}
}
@@ -114,21 +114,21 @@ mod schema {
#[schema(as = SignIn::ErrorCode)]
#[status_code = "actix_web::http::StatusCode::NOT_ACCEPTABLE"]
pub enum ErrorCode {
/// Некорректное имя пользователя или пароль
/// Incorrect username or password.
IncorrectCredentials,
/// Недействительный токен VK ID
/// Invalid VK ID token.
InvalidVkAccessToken,
}
/// Internal
/// Тип авторизации
/// Type of authorization.
pub enum SignInData {
/// Имя пользователя и пароль
/// User and password name and password.
Default(Request),
/// Идентификатор привязанного аккаунта VK
/// Identifier of the attached account VK.
Vk(i32),
}
}

View File

@@ -50,10 +50,7 @@ async fn sign_up_combined(
(status = NOT_ACCEPTABLE, body = ResponseError<ErrorCode>)
))]
#[post("/sign-up")]
pub async fn sign_up(
data_json: Json<Request>,
app_state: web::Data<AppState>,
) -> ServiceResponse {
pub async fn sign_up(data_json: Json<Request>, app_state: web::Data<AppState>) -> ServiceResponse {
let data = data_json.into_inner();
sign_up_combined(
@@ -124,21 +121,21 @@ mod schema {
#[derive(Serialize, Deserialize, utoipa::ToSchema)]
#[schema(as = SignUp::Request)]
pub struct Request {
/// Имя пользователя
/// User name.
#[schema(examples("n08i40k"))]
pub username: String,
/// Пароль
/// Password.
pub password: String,
/// Группа
/// Group.
#[schema(examples("ИС-214/23"))]
pub group: String,
/// Роль
/// Role.
pub role: UserRole,
/// Версия установленного приложения Polytechnic+
/// Version of the installed Polytechnic+ application.
#[schema(examples("3.0.0"))]
pub version: String,
}
@@ -151,21 +148,21 @@ mod schema {
#[serde(rename_all = "camelCase")]
#[schema(as = SignUpVk::Request)]
pub struct Request {
/// Токен VK ID
/// VK ID token.
pub access_token: String,
/// Имя пользователя
/// User name.
#[schema(examples("n08i40k"))]
pub username: String,
/// Группа
/// Group.
#[schema(examples("ИС-214/23"))]
pub group: String,
/// Роль
/// Role.
pub role: UserRole,
/// Версия установленного приложения Polytechnic+
/// Version of the installed Polytechnic+ application.
#[schema(examples("3.0.0"))]
pub version: String,
}
@@ -178,44 +175,44 @@ mod schema {
#[schema(as = SignUp::ErrorCode)]
#[status_code = "actix_web::http::StatusCode::NOT_ACCEPTABLE"]
pub enum ErrorCode {
/// Передана роль ADMIN
/// Conveyed the role of Admin.
DisallowedRole,
/// Неизвестное название группы
/// Unknown name of the group.
InvalidGroupName,
/// Пользователь с таким именем уже зарегистрирован
/// User with this name is already registered.
UsernameAlreadyExists,
/// Недействительный токен VK ID
/// Invalid VK ID token.
InvalidVkAccessToken,
/// Пользователь с таким аккаунтом VK уже зарегистрирован
/// User with such an account VK is already registered.
VkAlreadyExists,
}
/// Internal
/// Данные для регистрации
/// Data for registration.
pub struct SignUpData {
/// Имя пользователя
/// User name.
pub username: String,
/// Пароль
/// Password.
///
/// Должен присутствовать даже если регистрация происходит с помощью токена VK ID
/// Should be present even if registration occurs using the VK ID token.
pub password: String,
/// Идентификатор аккаунта VK
/// Account identifier VK.
pub vk_id: Option<i32>,
/// Группа
/// Group.
pub group: String,
/// Роль
/// Role.
pub role: UserRole,
/// Версия установленного приложения Polytechnic+
/// Version of the installed Polytechnic+ application.
pub version: String,
}
@@ -302,10 +299,7 @@ mod tests {
test_env();
let app_state = static_app_state().await;
driver::users::delete_by_username(
&app_state,
&"test::sign_up_multiple".to_string(),
);
driver::users::delete_by_username(&app_state, &"test::sign_up_multiple".to_string());
let create = sign_up_client(SignUpPartial {
username: "test::sign_up_multiple".to_string(),

View File

@@ -25,10 +25,7 @@ use actix_web::{get, web};
),
))]
#[get("/group")]
pub async fn group(
user: SyncExtractor<User>,
app_state: web::Data<AppState>,
) -> ServiceResponse {
pub async fn group(user: SyncExtractor<User>, app_state: web::Data<AppState>) -> ServiceResponse {
// Prevent thread lock
let schedule_lock = app_state.schedule.lock().unwrap();
@@ -55,22 +52,22 @@ mod schema {
#[schema(as = GetGroup::Response)]
#[serde(rename_all = "camelCase")]
pub struct Response {
/// Расписание группы
/// Group schedule.
pub group: ScheduleEntry,
/// Устаревшая переменная
///
/// По умолчанию возвращается пустой список
/// ## Outdated variable.
///
/// By default, an empty list is returned.
#[deprecated = "Will be removed in future versions"]
pub updated: Vec<i32>,
/// Устаревшая переменная
/// ## Outdated variable.
///
/// По умолчанию начальная дата по Unix
/// By default, the initial date for unix.
#[deprecated = "Will be removed in future versions"]
pub updated_at: DateTime<Utc>,
}
#[allow(deprecated)]
impl From<ScheduleEntry> for Response {
fn from(group: ScheduleEntry) -> Self {
@@ -86,12 +83,12 @@ mod schema {
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[schema(as = GroupSchedule::ErrorCode)]
pub enum ErrorCode {
/// Расписания ещё не получены
/// Schedules have not yet been parsed.
#[status_code = "actix_web::http::StatusCode::SERVICE_UNAVAILABLE"]
#[display("Schedule not parsed yet.")]
NoSchedule,
/// Группа не найдена
/// Group not found.
#[status_code = "actix_web::http::StatusCode::NOT_FOUND"]
#[display("Required group not found.")]
NotFound,

View File

@@ -35,7 +35,7 @@ mod schema {
#[derive(Serialize, ToSchema)]
#[schema(as = GetGroupNames::Response)]
pub struct Response {
/// Список названий групп отсортированный в алфавитном порядке
/// List of group names sorted in alphabetical order.
#[schema(examples(json!(["ИС-214/23"])))]
pub names: Vec<String>,
}

View File

@@ -8,23 +8,23 @@ use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use utoipa::ToSchema;
/// Ответ от сервера с расписаниями
/// Response from schedule server.
#[derive(Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct ScheduleView {
/// ETag расписания на сервере политехникума
/// ETag schedules on polytechnic server.
etag: String,
/// Дата обновления расписания на сайте политехникума
/// Schedule update date on polytechnic website.
uploaded_at: DateTime<Utc>,
/// Дата последнего скачивания расписания с сервера политехникума
/// Date last downloaded from the Polytechnic server.
downloaded_at: DateTime<Utc>,
/// Расписание групп
/// Groups schedule.
groups: HashMap<String, ScheduleEntry>,
/// Расписание преподавателей
/// Teachers schedule.
teachers: HashMap<String, ScheduleEntry>,
}
@@ -33,7 +33,7 @@ pub struct ScheduleView {
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[schema(as = ScheduleShared::ErrorCode)]
pub enum ErrorCode {
/// Расписания ещё не получены
/// Schedules not yet parsed.
#[display("Schedule not parsed yet.")]
NoSchedule,
}
@@ -56,22 +56,22 @@ impl TryFrom<&web::Data<AppState>> for ScheduleView {
}
}
/// Статус кешированного расписаний
/// Cached schedule status.
#[derive(Serialize, Deserialize, ToSchema, ResponderJson)]
#[serde(rename_all = "camelCase")]
pub struct CacheStatus {
/// Хеш расписаний
/// Schedule hash.
pub cache_hash: String,
/// Требуется ли обновить ссылку на расписание
/// Whether the schedule reference needs to be updated.
pub cache_update_required: bool,
/// Дата последнего обновления кеша
/// Last cache update date.
pub last_cache_update: i64,
/// Дата обновления кешированного расписания
///
/// Определяется сервером политехникума
/// Cached schedule update date.
///
/// Determined by the polytechnic's server.
pub last_schedule_update: i64,
}

View File

@@ -53,18 +53,18 @@ mod schema {
#[schema(as = GetTeacher::Response)]
#[serde(rename_all = "camelCase")]
pub struct Response {
/// Расписание преподавателя
/// Teacher's schedule.
pub teacher: ScheduleEntry,
/// Устаревшая переменная
/// ## Deprecated variable.
///
/// По умолчанию возвращается пустой список
/// By default, an empty list is returned.
#[deprecated = "Will be removed in future versions"]
pub updated: Vec<i32>,
/// Устаревшая переменная
/// ## Deprecated variable.
///
/// По умолчанию начальная дата по Unix
/// Defaults to the Unix start date.
#[deprecated = "Will be removed in future versions"]
pub updated_at: DateTime<Utc>,
}
@@ -84,12 +84,12 @@ mod schema {
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[schema(as = TeacherSchedule::ErrorCode)]
pub enum ErrorCode {
/// Расписания ещё не получены
/// Schedules have not yet been parsed.
#[status_code = "actix_web::http::StatusCode::SERVICE_UNAVAILABLE"]
#[display("Schedule not parsed yet.")]
NoSchedule,
/// Преподаватель не найден
/// Teacher not found.
#[status_code = "actix_web::http::StatusCode::NOT_FOUND"]
#[display("Required teacher not found.")]
NotFound,

View File

@@ -35,7 +35,7 @@ mod schema {
#[derive(Serialize, ToSchema)]
#[schema(as = GetTeacherNames::Response)]
pub struct Response {
/// Список имён преподавателей отсортированный в алфавитном порядке
/// List of teacher names sorted alphabetically.
#[schema(examples(json!(["Хомченко Н.Е."])))]
pub names: Vec<String>,
}

View File

@@ -84,7 +84,7 @@ mod schema {
#[derive(Serialize, Deserialize, ToSchema)]
pub struct Request {
/// Ссылка на расписание
/// Schedule link.
pub url: String,
}
@@ -92,25 +92,26 @@ mod schema {
#[status_code = "actix_web::http::StatusCode::NOT_ACCEPTABLE"]
#[schema(as = SetDownloadUrl::ErrorCode)]
pub enum ErrorCode {
/// Передана ссылка с хостом отличающимся от politehnikum-eng.ru
/// Transferred link with host different from politehnikum-eng.ru.
#[display("URL with unknown host provided. Provide url with politehnikum-eng.ru host.")]
NonWhitelistedHost,
/// Не удалось получить мета-данные файла
/// Failed to retrieve file metadata.
#[display("Unable to retrieve metadata from the specified URL.")]
FetchFailed,
/// Не удалось скачать файл
/// Failed to download the file.
#[display("Unable to retrieve data from the specified URL.")]
DownloadFailed,
/// Ссылка ведёт на устаревшее расписание
/// The link leads to an outdated schedule.
///
/// Под устаревшим расписанием подразумевается расписание, которое было опубликовано раньше, чем уже имеется на данный момент
/// An outdated schedule refers to a schedule that was published earlier
/// than is currently available.
#[display("The schedule is older than it already is.")]
OutdatedSchedule,
/// Не удалось преобразовать расписание
/// Failed to parse the schedule.
#[display("{}", "_0.display()")]
InvalidSchedule(ParseError),
}

View File

@@ -112,7 +112,8 @@ pub mod user {
use crate::database::models::{User, UserRole};
use actix_macros::ResponderJson;
use serde::Serialize;
//noinspection SpellCheckingInspection
/// Используется для скрытия чувствительных полей, таких как хеш пароля или FCM
#[derive(Serialize, utoipa::ToSchema, ResponderJson)]
#[serde(rename_all = "camelCase")]
@@ -132,7 +133,7 @@ pub mod user {
/// Роль
role: UserRole,
/// Идентификатор прявязанного аккаунта VK
/// Идентификатор привязанного аккаунта VK
#[schema(examples(498094647, json!(null)))]
vk_id: Option<i32>,

View File

@@ -54,7 +54,7 @@ mod schema {
#[derive(Serialize, Deserialize, ToSchema)]
#[schema(as = ChangeGroup::Request)]
pub struct Request {
/// Название группы.
/// Group name.
pub group: String,
}
@@ -63,21 +63,21 @@ mod schema {
#[schema(as = ChangeGroup::ErrorCode)]
#[status_code = "actix_web::http::StatusCode::CONFLICT"]
pub enum ErrorCode {
/// Расписания ещё не получены.
/// Schedules have not yet been received.
#[display("Schedule not parsed yet.")]
#[status_code = "actix_web::http::StatusCode::SERVICE_UNAVAILABLE"]
NoSchedule,
/// Передано то же название группы, что есть на данный момент.
/// Passed the same group name that is currently there.
#[display("Passed the same group name as it is at the moment.")]
SameGroup,
/// Требуемая группа не существует.
/// The required group does not exist.
#[display("The required group does not exist.")]
#[status_code = "actix_web::http::StatusCode::NOT_FOUND"]
NotFound,
/// Ошибка на стороне сервера.
/// Server-side error.
#[display("Internal server error.")]
#[status_code = "actix_web::http::StatusCode::INTERNAL_SERVER_ERROR"]
InternalServerError,

View File

@@ -45,7 +45,7 @@ mod schema {
#[derive(Serialize, Deserialize, ToSchema)]
#[schema(as = ChangeUsername::Request)]
pub struct Request {
/// Новое имя.
/// User name.
pub username: String,
}
@@ -54,15 +54,15 @@ mod schema {
#[schema(as = ChangeUsername::ErrorCode)]
#[status_code = "actix_web::http::StatusCode::CONFLICT"]
pub enum ErrorCode {
/// Передано то же имя, что есть на данный момент.
/// The same name that is currently present is passed.
#[display("Passed the same name as it is at the moment.")]
SameUsername,
/// Пользователь с таким именем уже существует.
/// A user with this name already exists.
#[display("A user with this name already exists.")]
AlreadyExists,
/// Ошибка на стороне сервера.
/// Server-side error.
#[display("Internal server error.")]
#[status_code = "actix_web::http::StatusCode::INTERNAL_SERVER_ERROR"]
InternalServerError,

View File

@@ -84,13 +84,13 @@ mod schema {
#[serde(rename_all = "camelCase")]
#[schema(as = VkIdOAuth::Request)]
pub struct Request {
/// Код подтверждения authorization_code
/// Код подтверждения authorization_code.
pub code: String,
/// Параметр для защиты передаваемых данных
/// Parameter to protect transmitted data.
pub code_verifier: String,
/// Идентификатор устройства
/// Device ID.
pub device_id: String,
}
@@ -98,7 +98,7 @@ mod schema {
#[serde(rename_all = "camelCase")]
#[schema(as = VkIdOAuth::Response)]
pub struct Response {
/// ID токен
/// ID token.
pub access_token: String,
}
@@ -107,7 +107,7 @@ mod schema {
#[schema(as = VkIdOAuth::ErrorCode)]
#[status_code = "actix_web::http::StatusCode::NOT_ACCEPTABLE"]
pub enum ErrorCode {
/// Сервер VK вернул ошибку
/// VK server returned an error.
#[display("VK server returned an error")]
VkIdError,
}