1 Commits

Author SHA1 Message Date
dependabot[bot]
0e4d34c284 Bump env_logger from 0.11.7 to 0.11.8
Bumps [env_logger](https://github.com/rust-cli/env_logger) from 0.11.7 to 0.11.8.
- [Release notes](https://github.com/rust-cli/env_logger/releases)
- [Changelog](https://github.com/rust-cli/env_logger/blob/main/CHANGELOG.md)
- [Commits](https://github.com/rust-cli/env_logger/compare/v0.11.7...v0.11.8)

---
updated-dependencies:
- dependency-name: env_logger
  dependency-version: 0.11.8
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-04-07 19:18:13 +00:00
55 changed files with 612 additions and 2622 deletions

View File

@@ -1,169 +0,0 @@
name: release
on:
push:
tags: [ "release/v*" ]
permissions:
contents: write
env:
CARGO_TERM_COLOR: always
BINARY_NAME: schedule-parser-rusted
TEST_DB: ${{ secrets.TEST_DATABASE_URL }}
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
SENTRY_ORG: ${{ secrets.SENTRY_ORG }}
SENTRY_PROJECT: ${{ secrets.SENTRY_PROJECT }}
DOCKER_IMAGE_NAME: ${{ github.repository }}
DOCKER_REGISTRY_HOST: registry.n08i40k.ru
DOCKER_REGISTRY_USERNAME: ${{ github.repository_owner }}
DOCKER_REGISTRY_PASSWORD: ${{ secrets.DOCKER_REGISTRY_PASSWORD }}
jobs:
test:
name: Test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Rust
uses: actions-rust-lang/setup-rust-toolchain@v1.11.0
with:
toolchain: stable
- name: Test
run: |
touch .env.test
cargo test --verbose
env:
DATABASE_URL: ${{ env.TEST_DB }}
JWT_SECRET: "test-secret-at-least-256-bits-used"
VKID_CLIENT_ID: 0
VKID_REDIRECT_URI: "vk0://vk.com/blank.html"
REQWEST_USER_AGENT: "Dalvik/2.1.0 (Linux; U; Android 6.0.1; OPPO R9s Build/MMB29M)"
build:
name: Build
runs-on: ubuntu-latest
needs: test
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Rust
uses: actions-rust-lang/setup-rust-toolchain@v1.11.0
with:
toolchain: stable
- name: Build
run: cargo build --release --verbose
- name: Extract debug symbols
run: |
objcopy --only-keep-debug target/release/${{ env.BINARY_NAME }}{,.d}
objcopy --strip-debug --strip-unneeded target/release/${{ env.BINARY_NAME }}
objcopy --add-gnu-debuglink target/release/${{ env.BINARY_NAME }}{.d,}
- name: Setup sentry-cli
uses: matbour/setup-sentry-cli@v2.0.0
with:
version: latest
token: ${{ env.SENTRY_AUTH_TOKEN }}
organization: ${{ env.SENTRY_ORG }}
project: ${{ env.SENTRY_PROJECT }}
- name: Upload debug symbols to Sentry
run: |
sentry-cli debug-files upload --include-sources .
- name: Upload build binary artifact
uses: actions/upload-artifact@v4
with:
name: release-binary
path: target/release/${{ env.BINARY_NAME }}
- name: Upload build debug symbols artifact
uses: actions/upload-artifact@v4
with:
name: release-symbols
path: target/release/${{ env.BINARY_NAME }}.d
docker:
name: Build & Push Docker Image
runs-on: ubuntu-latest
needs: build
steps:
- uses: actions/checkout@v4
- name: Download build artifacts
uses: actions/download-artifact@v4
with:
name: release-binary
- name: Setup Docker Buildx
uses: docker/setup-buildx-action@v3.10.0
- name: Login to Registry
uses: docker/login-action@v3.4.0
with:
registry: ${{ env.DOCKER_REGISTRY_HOST }}
username: ${{ env.DOCKER_REGISTRY_USERNAME }}
password: ${{ env.DOCKER_REGISTRY_PASSWORD }}
- name: Extract Docker metadata
id: meta
uses: docker/metadata-action@v5.7.0
with:
images: ${{ env.DOCKER_REGISTRY_HOST }}/${{ env.DOCKER_IMAGE_NAME }}
- name: Build and push Docker image
id: build-and-push
uses: docker/build-push-action@v6.15.0
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
build-args: |
"BINARY_NAME=${{ env.BINARY_NAME }}"
release:
name: Create GitHub Release
runs-on: ubuntu-latest
needs:
- build
- docker
# noinspection GrazieInspection,SpellCheckingInspection
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Generate changelog
run: |
LAST_TAG=$(git describe --tags --abbrev=0 HEAD^)
echo "## Коммиты с прошлого релиза $LAST_TAG" > CHANGELOG.md
git log $LAST_TAG..HEAD --oneline >> CHANGELOG.md
- name: Download build artifacts
uses: actions/download-artifact@v4
with:
pattern: release-*
merge-multiple: true
- name: Create Release
id: create_release
uses: ncipollo/release-action@v1.16.0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
artifacts: "${{ env.BINARY_NAME }},${{ env.BINARY_NAME }}.d"
bodyFile: CHANGELOG.md

View File

@@ -1,9 +1,10 @@
name: cargo test
name: Tests
on:
push:
branches: [ "master" ]
tags-ignore: [ "release/v*" ]
pull_request:
branches: [ "master" ]
permissions:
contents: read
@@ -26,7 +27,4 @@ jobs:
run: cargo test
env:
DATABASE_URL: ${{ secrets.TEST_DATABASE_URL }}
JWT_SECRET: "test-secret-at-least-256-bits-used"
VKID_CLIENT_ID: 0
VKID_REDIRECT_URI: "vk0://vk.com/blank.html"
REQWEST_USER_AGENT: "Dalvik/2.1.0 (Linux; U; Android 6.0.1; OPPO R9s Build/MMB29M)"
JWT_SECRET: "test-secret-at-least-256-bits-used"

3
.gitignore vendored
View File

@@ -3,5 +3,4 @@
schedule.json
teachers.json
.env*
/*-firebase-adminsdk-*.json
.env*

View File

@@ -10,7 +10,6 @@
<excludeFolder url="file://$MODULE_DIR$/actix-macros/target" />
<excludeFolder url="file://$MODULE_DIR$/actix-test/target" />
<excludeFolder url="file://$MODULE_DIR$/target" />
<excludeFolder url="file://$MODULE_DIR$/.idea/dataSources" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />

9
.idea/sqldialects.xml generated Normal file
View File

@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="SqlDialectMappings">
<file url="file://$PROJECT_DIR$/migrations/2025-03-21-211822_create_user_role/down.sql" dialect="PostgreSQL" />
<file url="file://$PROJECT_DIR$/migrations/2025-03-21-212111_create_users/up.sql" dialect="PostgreSQL" />
<file url="file://$PROJECT_DIR$/migrations/2025-03-21-212723_create_fcm/down.sql" dialect="PostgreSQL" />
<file url="file://$PROJECT_DIR$/migrations/2025-03-21-212723_create_fcm/up.sql" dialect="PostgreSQL" />
</component>
</project>

1000
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -3,13 +3,10 @@ members = ["actix-macros", "actix-test"]
[package]
name = "schedule-parser-rusted"
version = "1.0.1"
version = "0.8.0"
edition = "2024"
publish = false
[profile.release]
debug = true
[dependencies]
actix-web = "4.10.2"
actix-macros = { path = "actix-macros" }
@@ -20,8 +17,7 @@ derive_more = "2.0.1"
diesel = { version = "2.2.8", features = ["postgres"] }
diesel-derive-enum = { git = "https://github.com/Havunen/diesel-derive-enum.git", features = ["postgres"] }
dotenvy = "0.15.7"
env_logger = "0.11.7"
firebase-messaging-rs = { git = "https://github.com/i10416/firebase-messaging-rs.git" }
env_logger = "0.11.8"
futures-util = "0.3.31"
fuzzy-matcher = "0.3.7"
jsonwebtoken = { version = "9.3.1", features = ["use_pem"] }
@@ -29,9 +25,7 @@ hex = "0.4.3"
mime = "0.3.17"
objectid = "0.2.0"
regex = "1.11.1"
reqwest = { version = "0.12.15", features = ["json"] }
sentry = "0.37.0"
sentry-actix = "0.37.0"
reqwest = "0.12.15"
serde = { version = "1.0.219", features = ["derive"] }
serde_json = "1.0.140"
serde_with = "3.12.0"
@@ -42,7 +36,6 @@ rand = "0.9.0"
utoipa = { version = "5", features = ["actix_extras", "chrono"] }
utoipa-rapidoc = { version = "6.0.0", features = ["actix-web"] }
utoipa-actix-web = "0.1"
uuid = { version = "1.16.0", features = ["v4"] }
[dev-dependencies]
actix-test = { path = "actix-test" }

View File

@@ -1,14 +0,0 @@
FROM debian:stable-slim
LABEL authors="n08i40k"
ARG BINARY_NAME
WORKDIR /app/
RUN apt update && \
apt install -y libpq5
COPY ./${BINARY_NAME} /bin/main
RUN chmod +x /bin/main
ENTRYPOINT ["main"]

View File

@@ -1,4 +1,4 @@
-- This file was automatically created by Diesel to set up helper functions
-- This file was automatically created by Diesel to setup helper functions
-- and other internal bookkeeping. This file is safe to edit, any future
-- changes will be added to existing projects as new migrations.

View File

@@ -1,4 +1,4 @@
-- This file was automatically created by Diesel to set up helper functions
-- This file was automatically created by Diesel to setup helper functions
-- and other internal bookkeeping. This file is safe to edit, any future
-- changes will be added to existing projects as new migrations.

View File

@@ -2,7 +2,7 @@ CREATE TABLE users
(
id text PRIMARY KEY NOT NULL,
username text UNIQUE NOT NULL,
password text NOT NULL,
"password" text NOT NULL,
vk_id int4 NULL,
access_token text UNIQUE NOT NULL,
"group" text NOT NULL,

View File

@@ -1,6 +1,11 @@
CREATE TABLE fcm
(
user_id text PRIMARY KEY NOT NULL REFERENCES users (id),
user_id text PRIMARY KEY NOT NULL,
token text NOT NULL,
topics text[] NOT NULL CHECK ( array_position(topics, null) is null )
);
topics text[] NULL
);
CREATE UNIQUE INDEX fcm_user_id_key ON fcm USING btree (user_id);
ALTER TABLE fcm
ADD CONSTRAINT fcm_user_id_fkey FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE RESTRICT ON UPDATE CASCADE;

View File

@@ -4,11 +4,10 @@ use crate::xls_downloader::basic_impl::BasicXlsDownloader;
use actix_web::web;
use chrono::{DateTime, Utc};
use diesel::{Connection, PgConnection};
use firebase_messaging_rs::FCMClient;
use sha1::{Digest, Sha1};
use std::env;
use std::hash::Hash;
use std::sync::Mutex;
use std::sync::{Mutex, MutexGuard};
#[derive(Clone)]
pub struct Schedule {
@@ -19,24 +18,6 @@ pub struct Schedule {
pub data: ParseResult,
}
#[derive(Clone)]
pub struct VkId {
pub client_id: i32,
pub redirect_url: String,
}
impl VkId {
pub fn new() -> Self {
Self {
client_id: env::var("VKID_CLIENT_ID")
.expect("VKID_CLIENT_ID must be set")
.parse()
.expect("VKID_CLIENT_ID must be integer"),
redirect_url: env::var("VKID_REDIRECT_URI").expect("VKID_REDIRECT_URI must be set"),
}
}
}
impl Schedule {
pub fn hash(&self) -> String {
let mut hasher = DigestHasher::from(Sha1::new());
@@ -50,39 +31,30 @@ impl Schedule {
}
}
/// Common data provided to endpoints.
/// Общие данные передаваемые в эндпоинты
pub struct AppState {
pub downloader: Mutex<BasicXlsDownloader>,
pub schedule: Mutex<Option<Schedule>>,
pub database: Mutex<PgConnection>,
pub vk_id: VkId,
pub fcm_client: Option<Mutex<FCMClient>>, // в рантайме не меняется, так что опционален мьютекс, а не данные в нём.
}
impl AppState {
pub async fn new() -> Self {
let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
Self {
downloader: Mutex::new(BasicXlsDownloader::new()),
schedule: Mutex::new(None),
database: Mutex::new(
PgConnection::establish(&database_url)
.unwrap_or_else(|_| panic!("Error connecting to {}", database_url)),
),
vk_id: VkId::new(),
fcm_client: if env::var("GOOGLE_APPLICATION_CREDENTIALS").is_ok() {
Some(Mutex::new(
FCMClient::new().await.expect("FCM client must be created"),
))
} else {
None
},
}
/// Получение объекта соединения с базой данных PostgreSQL
pub fn connection(&self) -> MutexGuard<PgConnection> {
self.database.lock().unwrap()
}
}
/// Create a new object web::Data<AppState>.
pub async fn app_state() -> web::Data<AppState> {
web::Data::new(AppState::new().await)
/// Создание нового объекта web::Data<AppState>
pub fn app_state() -> web::Data<AppState> {
let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
web::Data::new(AppState {
downloader: Mutex::new(BasicXlsDownloader::new()),
schedule: Mutex::new(None),
database: Mutex::new(
PgConnection::establish(&database_url)
.unwrap_or_else(|_| panic!("Error connecting to {}", database_url)),
),
})
}

View File

@@ -1,163 +1,103 @@
pub mod users {
use crate::app_state::AppState;
use crate::database::models::User;
use crate::database::schema::users::dsl::users;
use crate::database::schema::users::dsl::*;
use crate::utility::mutex::MutexScope;
use actix_web::web;
use diesel::{ExpressionMethods, QueryResult, insert_into};
use diesel::{PgConnection, SelectableHelper};
use diesel::{QueryDsl, RunQueryDsl};
use diesel::{SaveChangesDsl, SelectableHelper};
use std::ops::DerefMut;
use std::sync::Mutex;
pub fn get(state: &web::Data<AppState>, _id: &String) -> QueryResult<User> {
state.database.scope(|conn| {
users
.filter(id.eq(_id))
.select(User::as_select())
.first(conn)
})
pub fn get(connection: &Mutex<PgConnection>, _id: &String) -> QueryResult<User> {
let mut lock = connection.lock().unwrap();
let con = lock.deref_mut();
users
.filter(id.eq(_id))
.select(User::as_select())
.first(con)
}
pub fn get_by_username(state: &web::Data<AppState>, _username: &String) -> QueryResult<User> {
state.database.scope(|conn| {
users
.filter(username.eq(_username))
.select(User::as_select())
.first(conn)
})
pub fn get_by_username(
connection: &Mutex<PgConnection>,
_username: &String,
) -> QueryResult<User> {
let mut lock = connection.lock().unwrap();
let con = lock.deref_mut();
users
.filter(username.eq(_username))
.select(User::as_select())
.first(con)
}
//noinspection RsTraitObligations
pub fn get_by_vk_id(state: &web::Data<AppState>, _vk_id: i32) -> QueryResult<User> {
state.database.scope(|conn| {
users
.filter(vk_id.eq(_vk_id))
.select(User::as_select())
.first(conn)
})
pub fn get_by_vk_id(
connection: &Mutex<PgConnection>,
_vk_id: i32,
) -> QueryResult<User> {
let mut lock = connection.lock().unwrap();
let con = lock.deref_mut();
users
.filter(vk_id.eq(_vk_id))
.select(User::as_select())
.first(con)
}
//noinspection DuplicatedCode
pub fn contains_by_username(state: &web::Data<AppState>, _username: &String) -> bool {
// и как это нахуй сократить блять примеров нихуя нет, нихуя не работает
// как меня этот раст заебал уже
state.database.scope(|conn| {
match users
.filter(username.eq(_username))
.count()
.get_result::<i64>(conn)
{
Ok(count) => count > 0,
Err(_) => false,
}
})
}
pub fn contains_by_username(connection: &Mutex<PgConnection>, _username: &String) -> bool {
let mut lock = connection.lock().unwrap();
let con = lock.deref_mut();
//noinspection DuplicatedCode
//noinspection RsTraitObligations
pub fn contains_by_vk_id(state: &web::Data<AppState>, _vk_id: i32) -> bool {
state.database.scope(|conn| {
match users
.filter(vk_id.eq(_vk_id))
.count()
.get_result::<i64>(conn)
{
Ok(count) => count > 0,
Err(_) => false,
}
})
}
pub fn insert(state: &web::Data<AppState>, user: &User) -> QueryResult<usize> {
state
.database
.scope(|conn| insert_into(users).values(user).execute(conn))
}
/// Function declaration [User::save][UserSave::save].
pub trait UserSave {
/// Saves the user's changes to the database.
///
/// # Arguments
///
/// * `state`: The state of the actix-web application that stores the mutex of the [connection][diesel::PgConnection].
///
/// returns: `QueryResult<User>`
///
/// # Examples
///
/// ```
/// use crate::database::driver::users;
///
/// #[derive(Deserialize)]
/// struct Params {
/// pub username: String,
/// }
///
/// #[patch("/")]
/// async fn patch_user(
/// app_state: web::Data<AppState>,
/// user: SyncExtractor<User>,
/// web::Query(params): web::Query<Params>,
/// ) -> web::Json<User> {
/// let mut user = user.into_inner();
///
/// user.username = params.username;
///
/// match user.save(&app_state) {
/// Ok(user) => web::Json(user),
/// Err(e) => {
/// eprintln!("Failed to save user: {e}");
/// panic!();
/// }
/// }
/// }
/// ```
fn save(&self, state: &web::Data<AppState>) -> QueryResult<User>;
}
/// Implementation of [UserSave][UserSave] trait.
impl UserSave for User {
fn save(&self, state: &web::Data<AppState>) -> QueryResult<User> {
state.database.scope(|conn| self.save_changes::<Self>(conn))
match users
.filter(username.eq(_username))
.count()
.get_result::<i64>(con)
{
Ok(count) => count > 0,
Err(_) => false,
}
}
#[cfg(test)]
pub fn delete_by_username(state: &web::Data<AppState>, _username: &String) -> bool {
state.database.scope(|conn| {
match diesel::delete(users.filter(username.eq(_username))).execute(conn) {
Ok(count) => count > 0,
Err(_) => false,
}
})
pub fn contains_by_vk_id(connection: &Mutex<PgConnection>, _vk_id: i32) -> bool {
let mut lock = connection.lock().unwrap();
let con = lock.deref_mut();
match users
.filter(vk_id.eq(_vk_id))
.count()
.get_result::<i64>(con)
{
Ok(count) => count > 0,
Err(_) => false,
}
}
pub fn insert(connection: &Mutex<PgConnection>, user: &User) -> QueryResult<usize> {
let mut lock = connection.lock().unwrap();
let con = lock.deref_mut();
insert_into(users).values(user).execute(con)
}
#[cfg(test)]
pub fn insert_or_ignore(state: &web::Data<AppState>, user: &User) -> QueryResult<usize> {
state.database.scope(|conn| {
insert_into(users)
.values(user)
.on_conflict_do_nothing()
.execute(conn)
})
}
}
pub mod fcm {
use crate::app_state::AppState;
use crate::database::models::{FCM, User};
use crate::utility::mutex::MutexScope;
use actix_web::web;
use diesel::QueryDsl;
use diesel::RunQueryDsl;
use diesel::{BelongingToDsl, QueryResult, SelectableHelper};
pub fn from_user(state: &web::Data<AppState>, user: &User) -> QueryResult<FCM> {
state.database.scope(|conn| {
FCM::belonging_to(&user)
.select(FCM::as_select())
.get_result(conn)
})
pub fn delete_by_username(connection: &Mutex<PgConnection>, _username: &String) -> bool {
let mut lock = connection.lock().unwrap();
let con = lock.deref_mut();
match diesel::delete(users.filter(username.eq(_username))).execute(con) {
Ok(count) => count > 0,
Err(_) => false,
}
}
#[cfg(test)]
pub fn insert_or_ignore(connection: &Mutex<PgConnection>, user: &User) -> QueryResult<usize> {
let mut lock = connection.lock().unwrap();
let con = lock.deref_mut();
insert_into(users)
.values(user)
.on_conflict_do_nothing()
.execute(con)
}
}

View File

@@ -1,11 +1,16 @@
use actix_macros::ResponderJson;
use diesel::QueryId;
use diesel::prelude::*;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
#[derive(
Copy, Clone, PartialEq, Debug, Serialize, Deserialize, diesel_derive_enum::DbEnum, ToSchema,
diesel_derive_enum::DbEnum,
Serialize,
Deserialize,
Debug,
Clone,
Copy,
PartialEq,
utoipa::ToSchema,
)]
#[ExistingTypePath = "crate::database::schema::sql_types::UserRole"]
#[DbValueStyle = "UPPERCASE"]
@@ -20,65 +25,37 @@ pub enum UserRole {
Identifiable,
AsChangeset,
Queryable,
QueryId,
Selectable,
Serialize,
Insertable,
Debug,
ToSchema,
utoipa::ToSchema,
ResponderJson,
)]
#[diesel(table_name = crate::database::schema::users)]
#[diesel(treat_none_as_null = true)]
pub struct User {
/// Account UUID.
/// UUID аккаунта
pub id: String,
/// User name.
/// Имя пользователя
pub username: String,
/// BCrypt password hash.
/// BCrypt хеш пароля
pub password: String,
/// ID of the linked VK account.
/// Идентификатор привязанного аккаунта VK
pub vk_id: Option<i32>,
/// JWT access token.
/// JWT токен доступа
pub access_token: String,
/// Group.
/// Группа
pub group: String,
/// Role.
/// Роль
pub role: UserRole,
/// Version of the installed Polytechnic+ application.
/// Версия установленного приложения Polytechnic+
pub version: String,
}
#[derive(
Debug,
Clone,
Serialize,
Identifiable,
Queryable,
Selectable,
Insertable,
AsChangeset,
Associations,
ToSchema,
ResponderJson,
)]
#[diesel(belongs_to(User))]
#[diesel(table_name = crate::database::schema::fcm)]
#[diesel(primary_key(user_id))]
pub struct FCM {
/// Account UUID.
pub user_id: String,
/// FCM token.
pub token: String,
/// List of topics subscribed to by the user.
pub topics: Vec<Option<String>>,
}

View File

@@ -10,7 +10,7 @@ diesel::table! {
fcm (user_id) {
user_id -> Text,
token -> Text,
topics -> Array<Nullable<Text>>,
topics -> Nullable<Array<Nullable<Text>>>,
}
}

View File

@@ -1,13 +1,13 @@
use crate::app_state::AppState;
use crate::database::driver;
use crate::database::models::{FCM, User};
use crate::extractors::base::{FromRequestSync, SyncExtractor};
use crate::database::models::User;
use crate::extractors::base::FromRequestSync;
use crate::utility::jwt;
use actix_macros::ResponseErrorMessage;
use actix_web::body::BoxBody;
use actix_web::dev::Payload;
use actix_web::http::header;
use actix_web::{FromRequest, HttpRequest, web};
use actix_web::{HttpRequest, web};
use derive_more::Display;
use serde::{Deserialize, Serialize};
use std::fmt::Debug;
@@ -16,19 +16,19 @@ use std::fmt::Debug;
#[status_code = "actix_web::http::StatusCode::UNAUTHORIZED"]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Error {
/// There is no Authorization header in the request.
/// В запросе отсутствует заголовок Authorization
#[display("No Authorization header found")]
NoHeader,
/// Unknown authorization type other than Bearer.
/// Неизвестный тип авторизации, отличающийся от Bearer
#[display("Bearer token is required")]
UnknownAuthorizationType,
/// Invalid or expired access token.
/// Токен не действителен
#[display("Invalid or expired access token")]
InvalidAccessToken,
/// The user bound to the token is not found in the database.
/// Пользователь привязанный к токену не найден в базе данных
#[display("No user associated with access token")]
NoUser,
}
@@ -39,7 +39,7 @@ impl Error {
}
}
/// User extractor from request with Bearer access token.
/// Экстрактор пользователя из запроса с токеном
impl FromRequestSync for User {
type Error = actix_web::Error;
@@ -63,48 +63,6 @@ impl FromRequestSync for User {
let app_state = req.app_data::<web::Data<AppState>>().unwrap();
driver::users::get(&app_state, &user_id).map_err(|_| Error::NoUser.into())
}
}
pub struct UserExtractor<const FCM: bool> {
user: User,
fcm: Option<FCM>,
}
impl<const FCM: bool> UserExtractor<{ FCM }> {
pub fn user(&self) -> &User {
&self.user
}
pub fn fcm(&self) -> &Option<FCM> {
if !FCM {
panic!("FCM marked as not required, but it has been requested")
}
&self.fcm
}
}
/// Extractor of user and additional parameters from request with Bearer token.
impl<const FCM: bool> FromRequestSync for UserExtractor<{ FCM }> {
type Error = actix_web::Error;
fn from_request_sync(req: &HttpRequest, payload: &mut Payload) -> Result<Self, Self::Error> {
let user = SyncExtractor::<User>::from_request(req, payload)
.into_inner()?
.into_inner();
let app_state = req.app_data::<web::Data<AppState>>().unwrap();
Ok(Self {
fcm: if FCM {
driver::fcm::from_user(&app_state, &user).ok()
} else {
None
},
user,
})
driver::users::get(&app_state.database, &user_id).map_err(|_| Error::NoUser.into())
}
}

View File

@@ -2,64 +2,26 @@ use actix_web::dev::Payload;
use actix_web::{FromRequest, HttpRequest};
use futures_util::future::LocalBoxFuture;
use std::future::{Ready, ready};
use std::ops;
/// # Async extractor.
/// Asynchronous object extractor from a query.
/// Асинхронный экстрактор объектов из запроса
pub struct AsyncExtractor<T>(T);
impl<T> AsyncExtractor<T> {
#[allow(dead_code)]
/// Retrieve the object extracted with the extractor.
/// Получение объекта, извлечённого с помощью экстрактора
pub fn into_inner(self) -> T {
self.0
}
}
impl<T> ops::Deref for AsyncExtractor<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<T> ops::DerefMut for AsyncExtractor<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
pub trait FromRequestAsync: Sized {
type Error: Into<actix_web::Error>;
/// Asynchronous function for extracting data from a query.
///
/// returns: Result<Self, Self::Error>
///
/// # Examples
///
/// ```
/// struct User {
/// pub id: String,
/// pub username: String,
/// }
///
/// // TODO: Я вообще этот экстрактор не использую, нахуя мне тогда писать пример, если я не ебу как его использовать. Я забыл.
///
/// #[get("/")]
/// fn get_user_async(
/// user: web::AsyncExtractor<User>,
/// ) -> web::Json<User> {
/// let user = user.into_inner();
///
/// web::Json(user)
/// }
/// ```
/// Асинхронная функция для извлечения данных из запроса
async fn from_request_async(req: HttpRequest, payload: Payload) -> Result<Self, Self::Error>;
}
/// Реализация треита FromRequest для всех асинхронных экстракторов
impl<T: FromRequestAsync> FromRequest for AsyncExtractor<T> {
type Error = T::Error;
type Future = LocalBoxFuture<'static, Result<Self, Self::Error>>;
@@ -75,72 +37,24 @@ impl<T: FromRequestAsync> FromRequest for AsyncExtractor<T> {
}
}
/// # Sync extractor.
/// Synchronous object extractor from a query.
/// Синхронный экстрактор объектов из запроса
pub struct SyncExtractor<T>(T);
impl<T> SyncExtractor<T> {
/// Retrieving an object extracted with the extractor.
/// Получение объекта, извлечённого с помощью экстрактора
pub fn into_inner(self) -> T {
self.0
}
}
impl<T> ops::Deref for SyncExtractor<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<T> ops::DerefMut for SyncExtractor<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
pub trait FromRequestSync: Sized {
type Error: Into<actix_web::Error>;
/// Synchronous function for extracting data from a query.
///
/// returns: Result<Self, Self::Error>
///
/// # Examples
///
/// ```
/// struct User {
/// pub id: String,
/// pub username: String,
/// }
///
/// impl FromRequestSync for User {
/// type Error = actix_web::Error;
///
/// fn from_request_sync(req: &HttpRequest, _: &mut Payload) -> Result<Self, Self::Error> {
/// // do magic here.
///
/// Ok(User {
/// id: "qwerty".to_string(),
/// username: "n08i40k".to_string()
/// })
/// }
/// }
///
/// #[get("/")]
/// fn get_user_sync(
/// user: web::SyncExtractor<User>,
/// ) -> web::Json<User> {
/// let user = user.into_inner();
///
/// web::Json(user)
/// }
/// ```
/// Синхронная функция для извлечения данных из запроса
fn from_request_sync(req: &HttpRequest, payload: &mut Payload) -> Result<Self, Self::Error>;
}
/// Реализация треита FromRequest для всех синхронных экстракторов
impl<T: FromRequestSync> FromRequest for SyncExtractor<T> {
type Error = T::Error;
type Future = Ready<Result<Self, Self::Error>>;

View File

@@ -1,12 +1,18 @@
use crate::app_state::{AppState, app_state};
use crate::middlewares::authorization::JWTAuthorization;
use crate::middlewares::content_type::ContentTypeBootstrap;
use actix_web::dev::{ServiceFactory, ServiceRequest};
use actix_web::{App, Error, HttpServer};
use crate::routes::auth::sign_in::{sign_in_default, sign_in_vk};
use crate::routes::auth::sign_up::{sign_up_default, sign_up_vk};
use crate::routes::schedule::get_cache_status::get_cache_status;
use crate::routes::schedule::get_group::get_group;
use crate::routes::schedule::get_group_names::get_group_names;
use crate::routes::schedule::get_schedule::get_schedule;
use crate::routes::schedule::get_teacher::get_teacher;
use crate::routes::schedule::get_teacher_names::get_teacher_names;
use crate::routes::schedule::update_download_url::update_download_url;
use crate::routes::users::me::me;
use actix_web::{App, HttpServer};
use dotenvy::dotenv;
use std::io;
use utoipa_actix_web::AppExt;
use utoipa_actix_web::scope::Scope;
use utoipa_rapidoc::RapiDoc;
mod app_state;
@@ -24,66 +30,45 @@ mod utility;
mod test_env;
pub fn get_api_scope<
I: Into<Scope<T>>,
T: ServiceFactory<ServiceRequest, Config = (), Error = Error, InitError = ()>,
>(
scope: I,
) -> Scope<T> {
let auth_scope = utoipa_actix_web::scope("/auth")
.service(routes::auth::sign_in)
.service(routes::auth::sign_in_vk)
.service(routes::auth::sign_up)
.service(routes::auth::sign_up_vk);
#[actix_web::main]
async fn main() {
dotenv().ok();
let users_scope = utoipa_actix_web::scope("/users")
.wrap(JWTAuthorization::default())
.service(routes::users::change_group)
.service(routes::users::change_username)
.service(routes::users::me);
unsafe { std::env::set_var("RUST_LOG", "debug") };
env_logger::init();
let schedule_scope = utoipa_actix_web::scope("/schedule")
.wrap(JWTAuthorization {
ignore: &["/group-names", "/teacher-names"],
})
.service(routes::schedule::schedule)
.service(routes::schedule::update_download_url)
.service(routes::schedule::cache_status)
.service(routes::schedule::group)
.service(routes::schedule::group_names)
.service(routes::schedule::teacher)
.service(routes::schedule::teacher_names);
let fcm_scope = utoipa_actix_web::scope("/fcm")
.wrap(JWTAuthorization::default())
.service(routes::fcm::update_callback)
.service(routes::fcm::set_token);
let vk_id_scope = utoipa_actix_web::scope("/vkid") //
.service(routes::vk_id::oauth);
utoipa_actix_web::scope(scope)
.service(auth_scope)
.service(users_scope)
.service(schedule_scope)
.service(fcm_scope)
.service(vk_id_scope)
}
async fn async_main() -> io::Result<()> {
println!("Starting server...");
let app_state = app_state().await;
let app_state = app_state();
HttpServer::new(move || {
let auth_scope = utoipa_actix_web::scope("/auth")
.service(sign_in_default)
.service(sign_in_vk)
.service(sign_up_default)
.service(sign_up_vk);
let users_scope = utoipa_actix_web::scope("/users")
.wrap(JWTAuthorization)
.service(me);
let schedule_scope = utoipa_actix_web::scope("/schedule")
.wrap(JWTAuthorization)
.service(get_schedule)
.service(update_download_url)
.service(get_cache_status)
.service(get_group)
.service(get_group_names)
.service(get_teacher)
.service(get_teacher_names);
let api_scope = utoipa_actix_web::scope("/api/v1")
.service(auth_scope)
.service(users_scope)
.service(schedule_scope);
let (app, api) = App::new()
.into_utoipa_app()
.app_data(app_state.clone())
.service(
get_api_scope("/api/v1")
.wrap(sentry_actix::Sentry::new())
.wrap(ContentTypeBootstrap),
)
.service(api_scope)
.split_for_parts();
let rapidoc_service = RapiDoc::with_openapi("/api-docs-json", api).path("/api-docs");
@@ -97,28 +82,9 @@ async fn async_main() -> io::Result<()> {
app.service(rapidoc_service.custom_html(patched_rapidoc_html))
})
.workers(4)
.bind(("0.0.0.0", 5050))?
.bind(("0.0.0.0", 8080))
.unwrap()
.run()
.await
}
fn main() -> io::Result<()> {
let _guard = sentry::init((
"https://9c33db76e89984b3f009b28a9f4b5954@sentry.n08i40k.ru/8",
sentry::ClientOptions {
release: sentry::release_name!(),
send_default_pii: true,
..Default::default()
},
));
unsafe { std::env::set_var("RUST_BACKTRACE", "1") };
dotenv().unwrap();
env_logger::init();
actix_web::rt::System::new().block_on(async { async_main().await })?;
Ok(())
.unwrap();
}

View File

@@ -7,17 +7,8 @@ use actix_web::{Error, HttpRequest, ResponseError};
use futures_util::future::LocalBoxFuture;
use std::future::{Ready, ready};
/// Middleware guard working with JWT tokens.
pub struct JWTAuthorization {
/// List of ignored endpoints.
pub ignore: &'static [&'static str],
}
impl Default for JWTAuthorization {
fn default() -> Self {
Self { ignore: &[] }
}
}
/// Middleware guard работающий с токенами JWT
pub struct JWTAuthorization;
impl<S, B> Transform<S, ServiceRequest> for JWTAuthorization
where
@@ -32,27 +23,22 @@ where
type Future = Ready<Result<Self::Transform, Self::InitError>>;
fn new_transform(&self, service: S) -> Self::Future {
ready(Ok(JWTAuthorizationMiddleware {
service,
ignore: self.ignore,
}))
ready(Ok(JWTAuthorizationMiddleware { service }))
}
}
pub struct JWTAuthorizationMiddleware<S> {
service: S,
/// List of ignored endpoints.
ignore: &'static [&'static str],
}
/// Функция для проверки наличия и действительности токена в запросе, а так же существования пользователя к которому он привязан
impl<S, B> JWTAuthorizationMiddleware<S>
where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
S::Future: 'static,
B: 'static,
{
/// Checking the validity of the token.
fn check_authorization(
pub fn check_authorization(
&self,
req: &HttpRequest,
payload: &mut Payload,
@@ -61,25 +47,9 @@ where
.map(|_| ())
.map_err(|e| e.as_error::<authorized_user::Error>().unwrap().clone())
}
fn should_skip(&self, req: &ServiceRequest) -> bool {
let path = req.match_info().unprocessed();
self.ignore.iter().any(|ignore| {
if !path.starts_with(ignore) {
return false;
}
if let Some(other) = path.as_bytes().iter().nth(ignore.len()) {
return ['?' as u8, '/' as u8].contains(other);
}
true
})
}
}
impl<'a, S, B> Service<ServiceRequest> for JWTAuthorizationMiddleware<S>
impl<S, B> Service<ServiceRequest> for JWTAuthorizationMiddleware<S>
where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
S::Future: 'static,
@@ -92,11 +62,6 @@ where
forward_ready!(service);
fn call(&self, req: ServiceRequest) -> Self::Future {
if self.should_skip(&req) {
let fut = self.service.call(req);
return Box::pin(async move { Ok(fut.await?.map_into_left_body()) });
}
let (http_req, mut payload) = req.into_parts();
if let Err(err) = self.check_authorization(&http_req, &mut payload) {

View File

@@ -1,64 +0,0 @@
use actix_web::Error;
use actix_web::body::{BoxBody, EitherBody};
use actix_web::dev::{Service, ServiceRequest, ServiceResponse, Transform, forward_ready};
use actix_web::http::header;
use actix_web::http::header::HeaderValue;
use futures_util::future::LocalBoxFuture;
use std::future::{Ready, ready};
/// Middleware to specify the encoding in the Content-Type header.
pub struct ContentTypeBootstrap;
impl<S, B> Transform<S, ServiceRequest> for ContentTypeBootstrap
where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
S::Future: 'static,
B: 'static,
{
type Response = ServiceResponse<EitherBody<B, BoxBody>>;
type Error = Error;
type Transform = ContentTypeMiddleware<S>;
type InitError = ();
type Future = Ready<Result<Self::Transform, Self::InitError>>;
fn new_transform(&self, service: S) -> Self::Future {
ready(Ok(ContentTypeMiddleware { service }))
}
}
pub struct ContentTypeMiddleware<S> {
service: S,
}
impl<'a, S, B> Service<ServiceRequest> for ContentTypeMiddleware<S>
where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
S::Future: 'static,
B: 'static,
{
type Response = ServiceResponse<EitherBody<B, BoxBody>>;
type Error = Error;
type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
forward_ready!(service);
fn call(&self, req: ServiceRequest) -> Self::Future {
let fut = self.service.call(req);
Box::pin(async move {
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"),
);
}
}
Ok(response.map_into_left_body())
})
}
}

View File

@@ -1,2 +1 @@
pub mod authorization;
pub mod content_type;
pub mod authorization;

View File

@@ -1,11 +1,10 @@
use crate::parser::LessonParseResult::{Lessons, Street};
use crate::parser::schema::LessonType::Break;
use crate::parser::schema::{
Day, ErrorCell, ErrorCellPos, Lesson, LessonSubGroup, LessonTime, LessonType, ParseError,
ParseResult, ScheduleEntry,
Day, Lesson, LessonSubGroup, LessonTime, LessonType, ParseError, ParseResult, ScheduleEntry,
};
use calamine::{Reader, Xls, open_workbook_from_rs};
use chrono::{DateTime, Duration, NaiveDateTime, Utc};
use chrono::{Duration, NaiveDateTime};
use fuzzy_matcher::FuzzyMatcher;
use fuzzy_matcher::skim::SkimMatcherV2;
use regex::Regex;
@@ -15,37 +14,39 @@ use std::sync::LazyLock;
pub mod schema;
/// Data cell storing the line.
/// Данные ячейке хранящей строку
struct InternalId {
/// Line index.
/// Индекс строки
row: u32,
/// Column index.
/// Индекс столбца
column: u32,
/// Text in the cell.
/**
* Текст в ячейке
*/
name: String,
}
/// Data on the time of lessons from the second column of the schedule.
/// Данные о времени проведения пар из второй колонки расписания
struct InternalTime {
/// Temporary segment of the lesson.
/// Временной отрезок проведения пары
time_range: LessonTime,
/// Type of lesson.
/// Тип пары
lesson_type: LessonType,
/// The lesson index.
/// Индекс пары
default_index: Option<u32>,
/// The frame of the cell.
/// Рамка ячейки
xls_range: ((u32, u32), (u32, u32)),
}
/// Working sheet type alias.
/// Сокращение типа рабочего листа
type WorkSheet = calamine::Range<calamine::Data>;
/// Getting a line from the required cell.
/// Получение строки из требуемой ячейки
fn get_string_from_cell(worksheet: &WorkSheet, row: u32, col: u32) -> Option<String> {
let cell_data = if let Some(data) = worksheet.get((row as usize, col as usize)) {
data.to_string()
@@ -57,8 +58,9 @@ fn get_string_from_cell(worksheet: &WorkSheet, row: u32, col: u32) -> Option<Str
return None;
}
static NL_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[\n\r]+").unwrap());
static SP_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\s+").unwrap());
static NL_RE: LazyLock<Regex, fn() -> Regex> =
LazyLock::new(|| Regex::new(r"[\n\r]+").unwrap());
static SP_RE: LazyLock<Regex, fn() -> Regex> = LazyLock::new(|| Regex::new(r"\s+").unwrap());
let trimmed_data = SP_RE
.replace_all(&NL_RE.replace_all(&cell_data, " "), " ")
@@ -72,7 +74,7 @@ fn get_string_from_cell(worksheet: &WorkSheet, row: u32, col: u32) -> Option<Str
}
}
/// Obtaining the boundaries of the cell along its upper left coordinate.
/// Получение границ ячейки по её верхней левой координате
fn get_merge_from_start(worksheet: &WorkSheet, row: u32, column: u32) -> ((u32, u32), (u32, u32)) {
let worksheet_end = worksheet.end().unwrap();
@@ -107,7 +109,7 @@ fn get_merge_from_start(worksheet: &WorkSheet, row: u32, column: u32) -> ((u32,
((row, column), (row_end, column_end))
}
/// Obtaining a "skeleton" schedule from the working sheet.
/// Получение "скелета" расписания из рабочего листа
fn parse_skeleton(worksheet: &WorkSheet) -> Result<(Vec<InternalId>, Vec<InternalId>), ParseError> {
let range = &worksheet;
@@ -165,20 +167,19 @@ fn parse_skeleton(worksheet: &WorkSheet) -> Result<(Vec<InternalId>, Vec<Interna
Ok((days, groups))
}
/// The result of obtaining a lesson from the cell.
/// Результат получения пары из ячейки
enum LessonParseResult {
/// List of lessons long from one to two.
/// Список пар длинной от одного до двух
///
/// The number of lessons will be equal to one if the couple is the first in the day,
/// otherwise the list from the change template and the lesson itself will be returned.
/// Количество пар будет равно одному, если пара первая за день, иначе будет возвращен список из шаблона перемены и самой пары
Lessons(Vec<Lesson>),
/// Street on which the Polytechnic Corps is located.
/// Улица на которой находится корпус политехникума
Street(String),
}
trait StringInnerSlice {
/// Obtaining a line from the line on the initial and final index.
/// Получения отрезка строки из строки по начальному и конечному индексу
fn inner_slice(&self, from: usize, to: usize) -> Self;
}
@@ -191,8 +192,7 @@ impl StringInnerSlice for String {
}
}
// noinspection GrazieInspection
/// Obtaining a non-standard type of lesson by name.
/// Получение нестандартного типа пары по названию
fn guess_lesson_type(name: &String) -> Option<(String, LessonType)> {
let map: HashMap<String, LessonType> = HashMap::from([
("(консультация)".to_string(), LessonType::Consultation),
@@ -234,7 +234,7 @@ fn guess_lesson_type(name: &String) -> Option<(String, LessonType)> {
}
}
/// Getting a pair or street from a cell.
/// Получение пары или улицы из ячейки
fn parse_lesson(
worksheet: &WorkSheet,
day: &mut Day,
@@ -252,7 +252,7 @@ fn parse_lesson(
let raw_name = raw_name_opt.unwrap();
static OTHER_STREET_RE: LazyLock<Regex> =
static OTHER_STREET_RE: LazyLock<Regex, fn() -> Regex> =
LazyLock::new(|| Regex::new(r"^[А-Я][а-я]+,?\s?[0-9]+$").unwrap());
if OTHER_STREET_RE.is_match(&raw_name) {
@@ -275,9 +275,7 @@ fn parse_lesson(
.filter(|time| time.xls_range.1.0 == cell_range.1.0)
.collect::<Vec<&InternalTime>>();
let end_time = end_time_arr
.first()
.ok_or(ParseError::LessonTimeNotFound(ErrorCellPos { row, column }))?;
let end_time = end_time_arr.first().ok_or(ParseError::LessonTimeNotFound)?;
let range: Option<[u8; 2]> = if time.default_index != None {
let default = time.default_index.unwrap() as u8;
@@ -371,7 +369,7 @@ fn parse_lesson(
])))
}
/// Obtaining a list of cabinets to the right of the lesson cell.
/// Получение списка кабинетов справа от ячейки пары
fn parse_cabinets(worksheet: &WorkSheet, row: u32, column: u32) -> Vec<String> {
let mut cabinets: Vec<String> = Vec::new();
@@ -389,14 +387,16 @@ fn parse_cabinets(worksheet: &WorkSheet, row: u32, column: u32) -> Vec<String> {
cabinets
}
/// Getting the "pure" name of the lesson and list of teachers from the text of the lesson cell.
/// Получение "чистого" названия пары и списка преподавателей из текста ячейки пары
fn parse_name_and_subgroups(name: &String) -> Result<(String, Vec<LessonSubGroup>), ParseError> {
static LESSON_RE: LazyLock<Regex> =
static LESSON_RE: LazyLock<Regex, fn() -> Regex> =
LazyLock::new(|| Regex::new(r"(?:[А-Я][а-я]+[А-Я]{2}(?:\([0-9][а-я]+\))?)+$").unwrap());
static TEACHER_RE: LazyLock<Regex> =
static TEACHER_RE: LazyLock<Regex, fn() -> Regex> =
LazyLock::new(|| Regex::new(r"([А-Я][а-я]+)([А-Я])([А-Я])(?:\(([0-9])[а-я]+\))?").unwrap());
static CLEAN_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[\s.,]+").unwrap());
static END_CLEAN_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[.\s]+$").unwrap());
static CLEAN_RE: LazyLock<Regex, fn() -> Regex> =
LazyLock::new(|| Regex::new(r"[\s.,]+").unwrap());
static END_CLEAN_RE: LazyLock<Regex, fn() -> Regex> =
LazyLock::new(|| Regex::new(r"[.\s]+$").unwrap());
let (teachers, lesson_name) = {
let clean_name = CLEAN_RE.replace_all(&name, "").to_string();
@@ -423,9 +423,14 @@ fn parse_name_and_subgroups(name: &String) -> Result<(String, Vec<LessonSubGroup
for captures in teacher_it {
subgroups.push(LessonSubGroup {
number: match captures.get(4) {
Some(capture) => capture.as_str().to_string().parse::<u8>().unwrap(),
None => 0,
number: if let Some(capture) = captures.get(4) {
capture
.as_str()
.to_string()
.parse::<u8>()
.map_err(|_| ParseError::SubgroupIndexParsingFailed)?
} else {
0
},
cabinet: None,
teacher: format!(
@@ -474,7 +479,7 @@ fn parse_name_and_subgroups(name: &String) -> Result<(String, Vec<LessonSubGroup
Ok((lesson_name, subgroups))
}
/// Conversion of the list of couples of groups in the list of lessons of teachers.
/// Конвертация списка пар групп в список пар преподавателей
fn convert_groups_to_teachers(
groups: &HashMap<String, ScheduleEntry>,
) -> HashMap<String, ScheduleEntry> {
@@ -551,26 +556,7 @@ fn convert_groups_to_teachers(
teachers
}
/// Reading XLS Document from the buffer and converting it into the schedule ready to use.
///
/// # Arguments
///
/// * `buffer`: XLS data containing schedule.
///
/// returns: Result<ParseResult, ParseError>
///
/// # Examples
///
/// ```
/// use schedule_parser_rusted::parser::parse_xls;
///
/// let result = parse_xls(&include_bytes!("../../schedule.xls").to_vec());
///
/// assert!(result.is_ok());
///
/// assert_ne!(result.as_ref().unwrap().groups.len(), 0);
/// assert_ne!(result.as_ref().unwrap().teachers.len(), 0);
/// ```
/// Чтение XLS документа из буфера и преобразование его в готовые к использованию расписания
pub fn parse_xls(buffer: &Vec<u8>) -> Result<ParseResult, ParseError> {
let cursor = Cursor::new(&buffer);
let mut workbook: Xls<_> =
@@ -660,12 +646,10 @@ pub fn parse_xls(buffer: &Vec<u8>) -> Result<ParseResult, ParseError> {
// time
let time_range = {
static TIME_RE: LazyLock<Regex> =
static TIME_RE: LazyLock<Regex, fn() -> Regex> =
LazyLock::new(|| Regex::new(r"(\d+\.\d+)-(\d+\.\d+)").unwrap());
let parse_res = TIME_RE.captures(&time).ok_or(ParseError::GlobalTime(
ErrorCell::new(row, lesson_time_column, time.clone()),
))?;
let parse_res = TIME_RE.captures(&time).ok_or(ParseError::GlobalTime)?;
let start_match = parse_res.get(1).unwrap().as_str();
let start_parts: Vec<&str> = start_match.split(".").collect();
@@ -673,15 +657,13 @@ pub fn parse_xls(buffer: &Vec<u8>) -> Result<ParseResult, ParseError> {
let end_match = parse_res.get(2).unwrap().as_str();
let end_parts: Vec<&str> = end_match.split(".").collect();
static GET_TIME: fn(DateTime<Utc>, &Vec<&str>) -> DateTime<Utc> =
|date, parts| {
date + Duration::hours(parts[0].parse::<i64>().unwrap() - 4)
+ Duration::minutes(parts[1].parse::<i64>().unwrap())
};
LessonTime {
start: GET_TIME(day.date.clone(), &start_parts),
end: GET_TIME(day.date.clone(), &end_parts),
start: day.date.clone()
+ Duration::hours(start_parts[0].parse().unwrap())
+ Duration::minutes(start_parts[1].parse().unwrap()),
end: day.date.clone()
+ Duration::hours(end_parts[0].parse().unwrap())
+ Duration::minutes(end_parts[1].parse().unwrap()),
}
};

View File

@@ -1,165 +1,144 @@
use chrono::{DateTime, Utc};
use derive_more::{Display, Error};
use derive_more::Display;
use serde::{Deserialize, Serialize, Serializer};
use serde_repr::{Deserialize_repr, Serialize_repr};
use std::collections::HashMap;
use std::sync::Arc;
use utoipa::ToSchema;
/// The beginning and end of the lesson.
#[derive(Clone, Hash, Debug, Serialize, Deserialize, ToSchema)]
pub struct LessonTime {
/// The beginning of a lesson.
/// Начало пары
pub start: DateTime<Utc>,
/// The end of the lesson.
/// Конец пары
pub end: DateTime<Utc>,
}
/// Type of lesson.
#[derive(Clone, Hash, PartialEq, Debug, Serialize_repr, Deserialize_repr, ToSchema)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[repr(u8)]
pub enum LessonType {
/// Обычная.
/// Обычная
Default = 0,
/// Допы.
/// Допы
Additional,
/// Перемена.
/// Перемена
Break,
/// Консультация.
/// Консультация
Consultation,
/// Самостоятельная работа.
/// Самостоятельная работа
IndependentWork,
/// Зачёт.
/// Зачёт
Exam,
/// Зачёт с оценкой.
/// Зачет с оценкой
ExamWithGrade,
/// Экзамен.
/// Экзамен
ExamDefault,
}
#[derive(Clone, Hash, Debug, Serialize, Deserialize, ToSchema)]
pub struct LessonSubGroup {
/// Index of subgroup.
/// Номер подгруппы
pub number: u8,
/// Cabinet, if present.
/// Кабинет, если присутствует
pub cabinet: Option<String>,
/// Full name of the teacher.
/// Фио преподавателя
pub teacher: String,
}
#[derive(Clone, Hash, Debug, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct Lesson {
/// Type.
/// Тип занятия
#[serde(rename = "type")]
pub lesson_type: LessonType,
/// Lesson indexes, if present.
/// Индексы пар, если присутствуют
pub default_range: Option<[u8; 2]>,
/// Name.
/// Название занятия
pub name: Option<String>,
/// The beginning and end.
/// Начало и конец занятия
pub time: LessonTime,
/// List of subgroups.
/// Список подгрупп
#[serde(rename = "subGroups")]
pub subgroups: Option<Vec<LessonSubGroup>>,
/// Group name, if this is a schedule for teachers.
/// Группа, если это расписание для преподавателей
pub group: Option<String>,
}
#[derive(Clone, Hash, Debug, Serialize, Deserialize, ToSchema)]
pub struct Day {
/// Day of the week.
/// День недели
pub name: String,
/// Address of another corps.
/// Адрес другого корпуса
pub street: Option<String>,
/// Date.
/// Дата
pub date: DateTime<Utc>,
/// List of lessons on this day.
/// Список пар в этот день
pub lessons: Vec<Lesson>,
}
#[derive(Clone, Hash, Debug, Serialize, Deserialize, ToSchema)]
pub struct ScheduleEntry {
/// The name of the group or name of the teacher.
/// Название группы или ФИО преподавателя
pub name: String,
/// List of six days.
/// Список из шести дней
pub days: Vec<Day>,
}
#[derive(Clone)]
pub struct ParseResult {
/// List of groups.
/// Список групп
pub groups: HashMap<String, ScheduleEntry>,
/// List of teachers.
/// Список преподавателей
pub teachers: HashMap<String, ScheduleEntry>,
}
#[derive(Clone, Debug, Display, Error, ToSchema)]
#[display("row {row}, column {column}")]
pub struct ErrorCellPos {
pub row: u32,
pub column: u32,
}
#[derive(Clone, Debug, Display, Error, ToSchema)]
#[display("'{data}' at {pos}")]
pub struct ErrorCell {
pub pos: ErrorCellPos,
pub data: String,
}
impl ErrorCell {
pub fn new(row: u32, column: u32, data: String) -> Self {
Self {
pos: ErrorCellPos { row, column },
data,
}
}
}
#[derive(Clone, Debug, Display, Error, ToSchema)]
#[derive(Debug, Display, Clone, ToSchema)]
pub enum ParseError {
/// Errors related to reading XLS file.
#[display("{_0:?}: Failed to read XLS file.")]
/// Ошибки связанные с чтением XLS файла.
#[display("{}: Failed to read XLS file.", "_0")]
#[schema(value_type = String)]
BadXLS(Arc<calamine::XlsError>),
/// Not a single sheet was found.
/// Не найдено ни одного листа
#[display("No work sheets found.")]
NoWorkSheets,
/// There are no data on the boundaries of the sheet.
/// Отсутствуют данные об границах листа
#[display("There is no data on work sheet boundaries.")]
UnknownWorkSheetRange,
/// Failed to read the beginning and end of the lesson from the line
#[display("Failed to read lesson start and end times from {_0}.")]
GlobalTime(ErrorCell),
/// Не удалось прочитать начало и конец пары из строки
#[display("Failed to read lesson start and end times from string.")]
GlobalTime,
/// Not found the beginning and the end corresponding to the lesson.
#[display("No start and end times matching the lesson (at {_0}) was found.")]
LessonTimeNotFound(ErrorCellPos),
/// Не найдены начало и конец соответствующее паре
#[display("No start and end times matching the lesson was found.")]
LessonTimeNotFound,
/// Не удалось прочитать индекс подгруппы
#[display("Failed to read subgroup index.")]
SubgroupIndexParsingFailed,
}
impl Serialize for ParseError {
@@ -173,8 +152,11 @@ impl Serialize for ParseError {
ParseError::UnknownWorkSheetRange => {
serializer.serialize_str("UNKNOWN_WORK_SHEET_RANGE")
}
ParseError::GlobalTime(_) => serializer.serialize_str("GLOBAL_TIME"),
ParseError::LessonTimeNotFound(_) => serializer.serialize_str("LESSON_TIME_NOT_FOUND"),
ParseError::GlobalTime => serializer.serialize_str("GLOBAL_TIME"),
ParseError::LessonTimeNotFound => serializer.serialize_str("LESSON_TIME_NOT_FOUND"),
ParseError::SubgroupIndexParsingFailed => {
serializer.serialize_str("SUBGROUP_INDEX_PARSING_FAILED")
}
}
}
}

View File

@@ -1,8 +1,3 @@
mod sign_in;
mod sign_up;
pub mod sign_in;
pub mod sign_up;
mod shared;
pub use sign_in::*;
pub use sign_up::*;
// TODO: change-password

View File

@@ -1,6 +1,9 @@
use crate::utility::jwt::DEFAULT_ALGORITHM;
use jsonwebtoken::errors::ErrorKind;
use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation};
use jsonwebtoken::{decode, DecodingKey, Validation};
use serde::{Deserialize, Serialize};
use std::env;
use std::sync::LazyLock;
#[derive(Deserialize, Serialize)]
struct TokenData {
@@ -14,7 +17,7 @@ struct TokenData {
#[derive(Debug, Serialize, Deserialize)]
struct Claims {
sub: i32,
sub: String,
iis: String,
jti: i32,
app: i32,
@@ -49,10 +52,17 @@ const VK_PUBLIC_KEY: &str = concat!(
"-----END PUBLIC KEY-----"
);
pub fn parse_vk_id(token_str: &String, client_id: i32) -> Result<i32, Error> {
static VK_ID_CLIENT_ID: LazyLock<i32> = LazyLock::new(|| {
env::var("VK_ID_CLIENT_ID")
.expect("VK_ID_CLIENT_ID must be set")
.parse::<i32>()
.expect("VK_ID_CLIENT_ID must be i32")
});
pub fn parse_vk_id(token_str: &String) -> Result<i32, Error> {
let dkey = DecodingKey::from_rsa_pem(VK_PUBLIC_KEY.as_bytes()).unwrap();
match decode::<Claims>(&token_str, &dkey, &Validation::new(Algorithm::RS256)) {
match decode::<Claims>(&token_str, &dkey, &Validation::new(DEFAULT_ALGORITHM)) {
Ok(token_data) => {
let claims = token_data.claims;
@@ -60,10 +70,13 @@ pub fn parse_vk_id(token_str: &String, client_id: i32) -> Result<i32, Error> {
Err(Error::UnknownIssuer(claims.iis))
} else if claims.jti != 21 {
Err(Error::UnknownType(claims.jti))
} else if claims.app != client_id {
} else if claims.app != *VK_ID_CLIENT_ID {
Err(Error::UnknownClientId(claims.app))
} else {
Ok(claims.sub)
match claims.sub.parse::<i32>() {
Ok(sub) => Ok(sub),
Err(_) => Err(Error::InvalidToken),
}
}
}
Err(err) => Err(match err.into_kind() {

View File

@@ -5,19 +5,19 @@ use crate::routes::auth::shared::parse_vk_id;
use crate::routes::auth::sign_in::schema::SignInData::{Default, Vk};
use crate::routes::schema::user::UserResponse;
use crate::routes::schema::{IntoResponseAsError, ResponseError};
use crate::utility::mutex::MutexScope;
use crate::{AppState, utility};
use crate::{utility, AppState};
use actix_web::{post, web};
use diesel::SaveChangesDsl;
use std::ops::DerefMut;
use web::Json;
async fn sign_in_combined(
async fn sign_in(
data: SignInData,
app_state: &web::Data<AppState>,
) -> Result<UserResponse, ErrorCode> {
let user = match &data {
Default(data) => driver::users::get_by_username(&app_state, &data.username),
Vk(id) => driver::users::get_by_vk_id(&app_state, *id),
Default(data) => driver::users::get_by_username(&app_state.database, &data.username),
Vk(id) => driver::users::get_by_vk_id(&app_state.database, *id),
};
match user {
@@ -35,12 +35,13 @@ async fn sign_in_combined(
}
}
let mut lock = app_state.connection();
let conn = lock.deref_mut();
user.access_token = utility::jwt::encode(&user.id);
app_state.database.scope(|conn| {
user.save_changes::<User>(conn)
.expect("Failed to update user")
});
user.save_changes::<User>(conn)
.expect("Failed to update user");
Ok(user.into())
}
@@ -54,10 +55,8 @@ async fn sign_in_combined(
(status = NOT_ACCEPTABLE, body = ResponseError<ErrorCode>)
))]
#[post("/sign-in")]
pub async fn sign_in(data: Json<Request>, app_state: web::Data<AppState>) -> ServiceResponse {
sign_in_combined(Default(data.into_inner()), &app_state)
.await
.into()
pub async fn sign_in_default(data: Json<Request>, app_state: web::Data<AppState>) -> ServiceResponse {
sign_in(Default(data.into_inner()), &app_state).await.into()
}
#[utoipa::path(responses(
@@ -65,14 +64,11 @@ pub async fn sign_in(data: Json<Request>, app_state: web::Data<AppState>) -> Ser
(status = NOT_ACCEPTABLE, body = ResponseError<ErrorCode>)
))]
#[post("/sign-in-vk")]
pub async fn sign_in_vk(
data_json: Json<vk::Request>,
app_state: web::Data<AppState>,
) -> ServiceResponse {
pub async fn sign_in_vk(data_json: Json<vk::Request>, app_state: web::Data<AppState>) -> ServiceResponse {
let data = data_json.into_inner();
match parse_vk_id(&data.access_token, app_state.vk_id.client_id) {
Ok(id) => sign_in_combined(Vk(id), &app_state).await.into(),
match parse_vk_id(&data.access_token) {
Ok(id) => sign_in(Vk(id), &app_state).await.into(),
Err(_) => ErrorCode::InvalidVkAccessToken.into_response(),
}
}
@@ -86,11 +82,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 +98,7 @@ mod schema {
#[serde(rename_all = "camelCase")]
#[schema(as = SignInVk::Request)]
pub struct Request {
/// VK ID token.
/// Токен VK ID
pub access_token: String,
}
}
@@ -114,21 +110,21 @@ mod schema {
#[schema(as = SignIn::ErrorCode)]
#[status_code = "actix_web::http::StatusCode::NOT_ACCEPTABLE"]
pub enum ErrorCode {
/// Incorrect username or password.
/// Некорректное имя пользователя или пароль
IncorrectCredentials,
/// Invalid VK ID token.
/// Недействительный токен VK ID
InvalidVkAccessToken,
}
/// Internal
/// Type of authorization.
/// Тип авторизации
pub enum SignInData {
/// User and password name and password.
/// Имя пользователя и пароль
Default(Request),
/// Identifier of the attached account VK.
/// Идентификатор привязанного аккаунта VK
Vk(i32),
}
}
@@ -138,7 +134,7 @@ mod tests {
use super::schema::*;
use crate::database::driver;
use crate::database::models::{User, UserRole};
use crate::routes::auth::sign_in::sign_in;
use crate::routes::auth::sign_in::sign_in_default;
use crate::test_env::tests::{static_app_state, test_app_state, test_env};
use crate::utility;
use actix_test::test_app;
@@ -150,7 +146,7 @@ mod tests {
use std::fmt::Write;
async fn sign_in_client(data: Request) -> ServiceResponse {
let app = test_app(test_app_state().await, sign_in).await;
let app = test_app(test_app_state(), sign_in_default).await;
let req = test::TestRequest::with_uri("/sign-in")
.method(Method::POST)
@@ -160,7 +156,7 @@ mod tests {
test::call_service(&app, req).await
}
async fn prepare(username: String) {
fn prepare(username: String) {
let id = {
let mut sha = Sha1::new();
sha.update(&username);
@@ -178,9 +174,9 @@ mod tests {
test_env();
let app_state = static_app_state().await;
let app_state = static_app_state();
driver::users::insert_or_ignore(
&app_state,
&app_state.database,
&User {
id: id.clone(),
username,
@@ -197,7 +193,7 @@ mod tests {
#[actix_web::test]
async fn sign_in_ok() {
prepare("test::sign_in_ok".to_string()).await;
prepare("test::sign_in_ok".to_string());
let resp = sign_in_client(Request {
username: "test::sign_in_ok".to_string(),
@@ -210,7 +206,7 @@ mod tests {
#[actix_web::test]
async fn sign_in_err() {
prepare("test::sign_in_err".to_string()).await;
prepare("test::sign_in_err".to_string());
let invalid_username = sign_in_client(Request {
username: "test::sign_in_err::username".to_string(),

View File

@@ -9,7 +9,7 @@ use actix_web::{post, web};
use rand::{Rng, rng};
use web::Json;
async fn sign_up_combined(
async fn sign_up(
data: SignUpData,
app_state: &web::Data<AppState>,
) -> Result<UserResponse, ErrorCode> {
@@ -28,19 +28,19 @@ async fn sign_up_combined(
}
// If user with specified username already exists.
if driver::users::contains_by_username(&app_state, &data.username) {
if driver::users::contains_by_username(&app_state.database, &data.username) {
return Err(ErrorCode::UsernameAlreadyExists);
}
// If user with specified VKID already exists.
if let Some(id) = data.vk_id {
if driver::users::contains_by_vk_id(&app_state, id) {
if driver::users::contains_by_vk_id(&app_state.database, id) {
return Err(ErrorCode::VkAlreadyExists);
}
}
let user = data.into();
driver::users::insert(&app_state, &user).unwrap();
driver::users::insert(&app_state.database, &user).unwrap();
Ok(UserResponse::from(&user)).into()
}
@@ -50,10 +50,13 @@ 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_default(
data_json: Json<Request>,
app_state: web::Data<AppState>,
) -> ServiceResponse {
let data = data_json.into_inner();
sign_up_combined(
sign_up(
SignUpData {
username: data.username,
password: data.password,
@@ -79,8 +82,8 @@ pub async fn sign_up_vk(
) -> ServiceResponse {
let data = data_json.into_inner();
match parse_vk_id(&data.access_token, app_state.vk_id.client_id) {
Ok(id) => sign_up_combined(
match parse_vk_id(&data.access_token) {
Ok(id) => sign_up(
SignUpData {
username: data.username,
password: rng()
@@ -121,21 +124,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,
/// Version of the installed Polytechnic+ application.
/// Версия установленного приложения Polytechnic+
#[schema(examples("3.0.0"))]
pub version: String,
}
@@ -148,21 +151,21 @@ mod schema {
#[serde(rename_all = "camelCase")]
#[schema(as = SignUpVk::Request)]
pub struct Request {
/// VK ID token.
/// Токен VK ID
pub access_token: String,
/// User name.
/// Имя пользователя
#[schema(examples("n08i40k"))]
pub username: String,
/// Group.
/// Группа
#[schema(examples("ИС-214/23"))]
pub group: String,
/// Role.
/// Роль
pub role: UserRole,
/// Version of the installed Polytechnic+ application.
/// Версия установленного приложения Polytechnic+
#[schema(examples("3.0.0"))]
pub version: String,
}
@@ -175,44 +178,44 @@ mod schema {
#[schema(as = SignUp::ErrorCode)]
#[status_code = "actix_web::http::StatusCode::NOT_ACCEPTABLE"]
pub enum ErrorCode {
/// Conveyed the role of Admin.
/// Передана роль ADMIN
DisallowedRole,
/// Unknown name of the group.
/// Неизвестное название группы
InvalidGroupName,
/// User with this name is already registered.
/// Пользователь с таким именем уже зарегистрирован
UsernameAlreadyExists,
/// Invalid VK ID token.
/// Недействительный токен VK ID
InvalidVkAccessToken,
/// User with such an account VK is already registered.
/// Пользователь с таким аккаунтом VK уже зарегистрирован
VkAlreadyExists,
}
/// Internal
/// Data for registration.
/// Данные для регистрации
pub struct SignUpData {
/// User name.
/// Имя пользователя
pub username: String,
/// Password.
/// Пароль
///
/// Should be present even if registration occurs using the VK ID token.
/// Должен присутствовать даже если регистрация происходит с помощью токена VK ID
pub password: String,
/// Account identifier VK.
/// Идентификатор аккаунта VK
pub vk_id: Option<i32>,
/// Group.
/// Группа
pub group: String,
/// Role.
/// Роль
pub role: UserRole,
/// Version of the installed Polytechnic+ application.
/// Версия установленного приложения Polytechnic+
pub version: String,
}
@@ -240,7 +243,7 @@ mod tests {
use crate::database::driver;
use crate::database::models::UserRole;
use crate::routes::auth::sign_up::schema::Request;
use crate::routes::auth::sign_up::sign_up;
use crate::routes::auth::sign_up::sign_up_default;
use crate::test_env::tests::{static_app_state, test_app_state, test_env};
use actix_test::test_app;
use actix_web::dev::ServiceResponse;
@@ -255,7 +258,7 @@ mod tests {
}
async fn sign_up_client(data: SignUpPartial) -> ServiceResponse {
let app = test_app(test_app_state().await, sign_up).await;
let app = test_app(test_app_state(), sign_up_default).await;
let req = test::TestRequest::with_uri("/sign-up")
.method(Method::POST)
@@ -277,8 +280,8 @@ mod tests {
test_env();
let app_state = static_app_state().await;
driver::users::delete_by_username(&app_state, &"test::sign_up_valid".to_string());
let app_state = static_app_state();
driver::users::delete_by_username(&app_state.database, &"test::sign_up_valid".to_string());
// test
@@ -298,8 +301,11 @@ mod tests {
test_env();
let app_state = static_app_state().await;
driver::users::delete_by_username(&app_state, &"test::sign_up_multiple".to_string());
let app_state = static_app_state();
driver::users::delete_by_username(
&app_state.database,
&"test::sign_up_multiple".to_string(),
);
let create = sign_up_client(SignUpPartial {
username: "test::sign_up_multiple".to_string(),

View File

@@ -1,5 +0,0 @@
mod update_callback;
mod set_token;
pub use update_callback::*;
pub use set_token::*;

View File

@@ -1,114 +0,0 @@
use crate::app_state::AppState;
use crate::database;
use crate::database::models::FCM;
use crate::extractors::authorized_user::UserExtractor;
use crate::extractors::base::SyncExtractor;
use crate::utility::mutex::{MutexScope, MutexScopeAsync};
use actix_web::{HttpResponse, Responder, patch, web};
use diesel::{RunQueryDsl, SaveChangesDsl};
use firebase_messaging_rs::FCMClient;
use firebase_messaging_rs::topic::{TopicManagementError, TopicManagementSupport};
use serde::Deserialize;
#[derive(Debug, Deserialize)]
struct Params {
pub token: String,
}
async fn get_fcm(
app_state: &web::Data<AppState>,
user_data: &UserExtractor<true>,
token: String,
) -> Result<FCM, diesel::result::Error> {
match user_data.fcm() {
Some(fcm) => {
let mut fcm = fcm.clone();
fcm.token = token;
Ok(fcm)
}
None => {
let fcm = FCM {
user_id: user_data.user().id.clone(),
token,
topics: vec![],
};
match app_state.database.scope(|conn| {
diesel::insert_into(database::schema::fcm::table)
.values(&fcm)
.execute(conn)
}) {
Ok(_) => Ok(fcm),
Err(e) => Err(e),
}
}
}
}
#[utoipa::path(responses((status = OK)))]
#[patch("/set-token")]
pub async fn set_token(
app_state: web::Data<AppState>,
web::Query(params): web::Query<Params>,
user_data: SyncExtractor<UserExtractor<true>>,
) -> impl Responder {
let user_data = user_data.into_inner();
// If token not changes - exit.
if let Some(fcm) = user_data.fcm() {
if fcm.token == params.token {
return HttpResponse::Ok();
}
}
let fcm = get_fcm(&app_state, &user_data, params.token.clone()).await;
if let Err(e) = fcm {
eprintln!("Failed to get FCM: {e}");
return HttpResponse::Ok();
}
let mut fcm = fcm.ok().unwrap();
// Add default topics.
if !fcm.topics.contains(&Some("common".to_string())) {
fcm.topics.push(Some("common".to_string()));
}
// Subscribe to default topics.
if let Some(e) = app_state
.fcm_client
.as_ref()
.unwrap()
.async_scope(
async |client: &mut FCMClient| -> Result<(), TopicManagementError> {
let mut tokens: Vec<String> = Vec::new();
tokens.push(fcm.token.clone());
for topic in fcm.topics.clone() {
if let Some(topic) = topic {
client.register_tokens_to_topic(topic.clone(), tokens.clone()).await?;
}
}
Ok(())
},
)
.await
.err()
{
eprintln!("Failed to subscribe token to topic: {:?}", e);
return HttpResponse::Ok();
}
// Write updates to db.
if let Some(e) = app_state
.database
.scope(|conn| fcm.save_changes::<FCM>(conn))
.err()
{
eprintln!("Failed to update FCM object: {e}");
}
HttpResponse::Ok()
}

View File

@@ -1,32 +0,0 @@
use crate::app_state::AppState;
use crate::database::models::User;
use crate::extractors::base::SyncExtractor;
use crate::utility::mutex::MutexScope;
use actix_web::{HttpResponse, Responder, post, web};
use diesel::SaveChangesDsl;
#[utoipa::path(responses(
(status = OK),
(status = INTERNAL_SERVER_ERROR)
))]
#[post("/update-callback/{version}")]
async fn update_callback(
app_state: web::Data<AppState>,
version: web::Path<String>,
user: SyncExtractor<User>,
) -> impl Responder {
let mut user = user.into_inner();
user.version = version.into_inner();
match app_state
.database
.scope(|conn| user.save_changes::<User>(conn))
{
Ok(_) => HttpResponse::Ok(),
Err(e) => {
eprintln!("Failed to update user: {}", e);
HttpResponse::InternalServerError()
}
}
}

View File

@@ -1,6 +1,4 @@
pub mod auth;
pub mod fcm;
pub mod users;
pub mod schedule;
mod schema;
pub mod users;
pub mod vk_id;

View File

@@ -6,7 +6,7 @@ use actix_web::{get, web};
(status = OK, body = CacheStatus),
))]
#[get("/cache-status")]
pub async fn cache_status(app_state: web::Data<AppState>) -> CacheStatus {
pub async fn get_cache_status(app_state: web::Data<AppState>) -> CacheStatus {
// Prevent thread lock
let has_schedule = app_state
.schedule

View File

@@ -25,7 +25,10 @@ use actix_web::{get, web};
),
))]
#[get("/group")]
pub async fn group(user: SyncExtractor<User>, app_state: web::Data<AppState>) -> ServiceResponse {
pub async fn get_group(
user: SyncExtractor<User>,
app_state: web::Data<AppState>,
) -> ServiceResponse {
// Prevent thread lock
let schedule_lock = app_state.schedule.lock().unwrap();
@@ -52,22 +55,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.
/// Устаревшая переменная
///
/// By default, the initial date for unix.
/// По умолчанию начальная дата по 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 {
@@ -83,12 +86,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

@@ -9,7 +9,7 @@ use actix_web::{get, web};
(status = SERVICE_UNAVAILABLE, body = ResponseError<ErrorCode>),
))]
#[get("/group-names")]
pub async fn group_names(app_state: web::Data<AppState>) -> ServiceResponse {
pub async fn get_group_names(app_state: web::Data<AppState>) -> ServiceResponse {
// Prevent thread lock
let schedule_lock = app_state.schedule.lock().unwrap();
@@ -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

@@ -9,7 +9,7 @@ use actix_web::{get, web};
(status = SERVICE_UNAVAILABLE, body = ResponseError<ErrorCode>)
))]
#[get("/")]
pub async fn schedule(app_state: web::Data<AppState>) -> ServiceResponse {
pub async fn get_schedule(app_state: web::Data<AppState>) -> ServiceResponse {
match ScheduleView::try_from(&app_state) {
Ok(res) => Ok(res).into(),
Err(e) => match e {

View File

@@ -23,7 +23,7 @@ use actix_web::{get, web};
),
))]
#[get("/teacher/{name}")]
pub async fn teacher(
pub async fn get_teacher(
name: web::Path<String>,
app_state: web::Data<AppState>,
) -> ServiceResponse {
@@ -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.
/// Устаревшая переменная
///
/// Defaults to the Unix start date.
/// По умолчанию начальная дата по Unix
#[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

@@ -9,7 +9,7 @@ use actix_web::{get, web};
(status = SERVICE_UNAVAILABLE, body = ResponseError<ErrorCode>),
))]
#[get("/teacher-names")]
pub async fn teacher_names(app_state: web::Data<AppState>) -> ServiceResponse {
pub async fn get_teacher_names(app_state: web::Data<AppState>) -> ServiceResponse {
// Prevent thread lock
let schedule_lock = app_state.schedule.lock().unwrap();
@@ -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

@@ -1,16 +1,8 @@
mod cache_status;
mod group;
mod group_names;
mod schedule;
mod teacher;
mod teacher_names;
pub mod get_cache_status;
pub mod get_schedule;
pub mod get_group;
pub mod get_group_names;
pub mod get_teacher;
pub mod get_teacher_names;
mod schema;
mod update_download_url;
pub use cache_status::*;
pub use group::*;
pub use group_names::*;
pub use schedule::*;
pub use teacher::*;
pub use teacher_names::*;
pub use update_download_url::*;
pub mod update_download_url;

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 schedules on polytechnic server.
/// ETag расписания на сервере политехникума
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

@@ -4,7 +4,7 @@ use crate::app_state::Schedule;
use crate::parser::parse_xls;
use crate::routes::schedule::schema::CacheStatus;
use crate::routes::schema::{IntoResponseAsError, ResponseError};
use crate::xls_downloader::interface::{FetchError, XLSDownloader};
use crate::xls_downloader::interface::XLSDownloader;
use actix_web::web::Json;
use actix_web::{patch, web};
use chrono::Utc;
@@ -41,7 +41,7 @@ pub async fn update_download_url(
}
match downloader.fetch(false).await {
Ok(download_result) => match parse_xls(&download_result.data.unwrap()) {
Ok(download_result) => match parse_xls(download_result.data.as_ref().unwrap()) {
Ok(data) => {
*schedule = Some(Schedule {
etag: download_result.etag,
@@ -53,25 +53,19 @@ pub async fn update_download_url(
Ok(CacheStatus::from(schedule.as_ref().unwrap())).into()
}
Err(error) => {
sentry::capture_error(&error);
ErrorCode::InvalidSchedule(error).into_response()
}
Err(error) => ErrorCode::InvalidSchedule(error).into_response(),
},
Err(error) => {
if let FetchError::Unknown(error) = error {
sentry::capture_error(&error);
}
eprintln!("Unknown url provided {}", data.url);
eprintln!("{:?}", error);
ErrorCode::DownloadFailed.into_response()
}
}
}
Err(error) => {
if let FetchError::Unknown(error) = error {
sentry::capture_error(&error);
}
eprintln!("Unknown url provided {}", data.url);
eprintln!("{:?}", error);
ErrorCode::FetchFailed.into_response()
}
@@ -90,7 +84,7 @@ mod schema {
#[derive(Serialize, Deserialize, ToSchema)]
pub struct Request {
/// Schedule link.
/// Ссылка на расписание
pub url: String,
}
@@ -98,27 +92,26 @@ mod schema {
#[status_code = "actix_web::http::StatusCode::NOT_ACCEPTABLE"]
#[schema(as = SetDownloadUrl::ErrorCode)]
pub enum ErrorCode {
/// Transferred link with host different from politehnikum-eng.ru.
#[display("URL with unknown host provided. Provide url with 'politehnikum-eng.ru' host.")]
/// Передана ссылка с хостом отличающимся от 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("{}", "_0.display()")]
InvalidSchedule(ParseError),
}

View File

@@ -112,8 +112,7 @@ 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")]
@@ -133,7 +132,7 @@ pub mod user {
/// Роль
role: UserRole,
/// Идентификатор привязанного аккаунта VK
/// Идентификатор прявязанного аккаунта VK
#[schema(examples(498094647, json!(null)))]
vk_id: Option<i32>,

View File

@@ -1,85 +0,0 @@
use self::schema::*;
use crate::app_state::AppState;
use crate::database::driver::users::UserSave;
use crate::database::models::User;
use crate::extractors::base::SyncExtractor;
use crate::routes::schema::IntoResponseAsError;
use crate::utility::mutex::MutexScope;
use actix_web::{post, web};
#[utoipa::path(responses((status = OK)))]
#[post("/change-group")]
pub async fn change_group(
app_state: web::Data<AppState>,
user: SyncExtractor<User>,
data: web::Json<Request>,
) -> ServiceResponse {
let mut user = user.into_inner();
if user.group == data.group {
return ErrorCode::SameGroup.into_response();
}
if let Some(e) = app_state.schedule.scope(|schedule| match schedule {
Some(schedule) => {
if schedule.data.groups.contains_key(&data.group) {
None
} else {
Some(ErrorCode::NotFound)
}
}
None => Some(ErrorCode::NoSchedule),
}) {
return e.into_response();
}
user.group = data.into_inner().group;
if let Some(e) = user.save(&app_state).err() {
eprintln!("Failed to update user: {e}");
return ErrorCode::InternalServerError.into_response();
}
Ok(()).into()
}
mod schema {
use actix_macros::{IntoResponseErrorNamed, StatusCode};
use derive_more::Display;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
pub type ServiceResponse = crate::routes::schema::Response<(), ErrorCode>;
#[derive(Serialize, Deserialize, ToSchema)]
#[schema(as = ChangeGroup::Request)]
pub struct Request {
/// Group name.
pub group: String,
}
#[derive(Clone, Serialize, ToSchema, StatusCode, Display, IntoResponseErrorNamed)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[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

@@ -1,70 +0,0 @@
use self::schema::*;
use crate::app_state::AppState;
use crate::database::driver;
use crate::database::driver::users::UserSave;
use crate::database::models::User;
use crate::extractors::base::SyncExtractor;
use crate::routes::schema::IntoResponseAsError;
use actix_web::{post, web};
#[utoipa::path(responses((status = OK)))]
#[post("/change-username")]
pub async fn change_username(
app_state: web::Data<AppState>,
user: SyncExtractor<User>,
data: web::Json<Request>,
) -> ServiceResponse {
let mut user = user.into_inner();
if user.username == data.username {
return ErrorCode::SameUsername.into_response();
}
if driver::users::get_by_username(&app_state, &data.username).is_ok() {
return ErrorCode::AlreadyExists.into_response();
}
user.username = data.into_inner().username;
if let Some(e) = user.save(&app_state).err() {
eprintln!("Failed to update user: {e}");
return ErrorCode::InternalServerError.into_response();
}
Ok(()).into()
}
mod schema {
use actix_macros::{IntoResponseErrorNamed, StatusCode};
use derive_more::Display;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
pub type ServiceResponse = crate::routes::schema::Response<(), ErrorCode>;
#[derive(Serialize, Deserialize, ToSchema)]
#[schema(as = ChangeUsername::Request)]
pub struct Request {
/// User name.
pub username: String,
}
#[derive(Clone, Serialize, ToSchema, StatusCode, Display, IntoResponseErrorNamed)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[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

@@ -1,7 +1 @@
mod change_group;
mod change_username;
mod me;
pub use change_group::*;
pub use change_username::*;
pub use me::*;
pub mod me;

View File

@@ -1,3 +0,0 @@
mod oauth;
pub use oauth::*;

View File

@@ -1,117 +0,0 @@
use self::schema::*;
use crate::app_state::AppState;
use crate::routes::schema::{IntoResponseAsError, ResponseError};
use actix_web::{post, web};
use serde::Deserialize;
use std::collections::HashMap;
use uuid::Uuid;
#[allow(dead_code)]
#[derive(Deserialize)]
struct VkIdAuthResponse {
refresh_token: String,
access_token: String,
id_token: String,
token_type: String,
expires_in: i32,
user_id: i32,
state: String,
scope: String,
}
#[utoipa::path(responses(
(status = OK, body = Response),
(
status = NOT_ACCEPTABLE,
body = ResponseError<ErrorCode>,
example = json!({
"code": "VK_ID_ERROR",
"message": "VK server returned an error"
})
),
))]
#[post("/oauth")]
async fn oauth(data: web::Json<Request>, app_state: web::Data<AppState>) -> ServiceResponse {
let data = data.into_inner();
let state = Uuid::new_v4().simple().to_string();
let vk_id = &app_state.vk_id;
let client_id = vk_id.client_id.clone().to_string();
let mut params = HashMap::new();
params.insert("grant_type", "authorization_code");
params.insert("client_id", client_id.as_str());
params.insert("state", state.as_str());
params.insert("code_verifier", data.code_verifier.as_str());
params.insert("code", data.code.as_str());
params.insert("device_id", data.device_id.as_str());
params.insert("redirect_uri", vk_id.redirect_url.as_str());
let client = reqwest::Client::new();
match client
.post("https://id.vk.com/oauth2/auth")
.form(&params)
.send()
.await
{
Ok(res) => {
if !res.status().is_success() {
return ErrorCode::VkIdError.into_response();
}
match res.json::<VkIdAuthResponse>().await {
Ok(auth_data) =>
Ok(Response {
access_token: auth_data.id_token,
}).into(),
Err(error) => {
sentry::capture_error(&error);
ErrorCode::VkIdError.into_response()
}
}
}
Err(_) => ErrorCode::VkIdError.into_response(),
}
}
mod schema {
use actix_macros::{IntoResponseErrorNamed, StatusCode};
use derive_more::Display;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
pub type ServiceResponse = crate::routes::schema::Response<Response, ErrorCode>;
#[derive(Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
#[schema(as = VkIdOAuth::Request)]
pub struct Request {
/// Код подтверждения authorization_code.
pub code: String,
/// Parameter to protect transmitted data.
pub code_verifier: String,
/// Device ID.
pub device_id: String,
}
#[derive(Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
#[schema(as = VkIdOAuth::Response)]
pub struct Response {
/// ID token.
pub access_token: String,
}
#[derive(Clone, Serialize, ToSchema, IntoResponseErrorNamed, StatusCode, Display)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[schema(as = VkIdOAuth::ErrorCode)]
#[status_code = "actix_web::http::StatusCode::NOT_ACCEPTABLE"]
pub enum ErrorCode {
/// VK server returned an error.
#[display("VK server returned an error")]
VkIdError,
}
}

View File

@@ -1,16 +1,16 @@
#[cfg(test)]
pub(crate) mod tests {
use crate::app_state::{AppState, Schedule, app_state};
use crate::app_state::{app_state, AppState, Schedule};
use crate::parser::tests::test_result;
use actix_web::web;
use tokio::sync::OnceCell;
use actix_web::{web};
use std::sync::LazyLock;
pub fn test_env() {
dotenvy::from_path(".env.test").expect("Failed to load test environment file");
}
pub async fn test_app_state() -> web::Data<AppState> {
let state = app_state().await;
pub fn test_app_state() -> web::Data<AppState> {
let state = app_state();
let mut schedule_lock = state.schedule.lock().unwrap();
*schedule_lock = Some(Schedule {
@@ -24,9 +24,9 @@ pub(crate) mod tests {
state.clone()
}
pub async fn static_app_state() -> web::Data<AppState> {
static STATE: OnceCell<web::Data<AppState>> = OnceCell::const_new();
pub fn static_app_state() -> web::Data<AppState> {
static STATE: LazyLock<web::Data<AppState>> = LazyLock::new(|| test_app_state());
STATE.get_or_init(|| test_app_state()).await.clone()
STATE.clone()
}
}

View File

@@ -2,7 +2,7 @@ use std::fmt::{Write};
use std::fmt::Display;
use serde::{Deserialize, Serialize};
/// Server response to errors within Middleware.
/// Ответ от сервера при ошибках внутри Middleware
#[derive(Serialize, Deserialize)]
pub struct ResponseErrorMessage<T: Display> {
code: T,

View File

@@ -1,7 +1,7 @@
use sha1::Digest;
use std::hash::Hasher;
/// Hesher returning hash from the algorithm implementing Digest
/// Хешер возвращающий хеш из алгоритма реализующего Digest
pub struct DigestHasher<D: Digest> {
digest: D,
}
@@ -10,7 +10,7 @@ impl<D> DigestHasher<D>
where
D: Digest,
{
/// Obtain hash.
/// Получение хеша
pub fn finalize(self) -> String {
hex::encode(self.digest.finalize().0)
}
@@ -20,14 +20,14 @@ impl<D> From<D> for DigestHasher<D>
where
D: Digest,
{
/// Creating a hash from an algorithm implementing Digest.
/// Создания хешера из алгоритма реализующего Digest
fn from(digest: D) -> Self {
DigestHasher { digest }
}
}
impl<D: Digest> Hasher for DigestHasher<D> {
/// Stopper to prevent calling the standard Hasher result.
/// Заглушка для предотвращения вызова стандартного результата Hasher
fn finish(&self) -> u64 {
unimplemented!("Do not call finish()");
}

View File

@@ -9,31 +9,31 @@ use std::env;
use std::mem::discriminant;
use std::sync::LazyLock;
/// Key for token verification.
/// Ключ для верификации токена
static DECODING_KEY: LazyLock<DecodingKey> = LazyLock::new(|| {
let secret = env::var("JWT_SECRET").expect("JWT_SECRET must be set");
DecodingKey::from_secret(secret.as_bytes())
});
/// Key for creating a signed token.
/// Ключ для создания подписанного токена
static ENCODING_KEY: LazyLock<EncodingKey> = LazyLock::new(|| {
let secret = env::var("JWT_SECRET").expect("JWT_SECRET must be set");
EncodingKey::from_secret(secret.as_bytes())
});
/// Token verification errors.
/// Ошибки верификации токена
#[allow(dead_code)]
#[derive(Debug)]
pub enum Error {
/// The token has a different signature.
/// Токен имеет другую подпись
InvalidSignature,
/// Token reading error.
/// Ошибка чтения токена
InvalidToken(ErrorKind),
/// Token expired.
/// Токен просрочен
Expired,
}
@@ -43,26 +43,26 @@ impl PartialEq for Error {
}
}
/// The data the token holds.
/// Данные, которые хранит в себе токен
#[serde_as]
#[derive(Debug, Serialize, Deserialize)]
struct Claims {
/// User account UUID.
/// UUID аккаунта пользователя
id: String,
/// Token creation date.
/// Дата создания токена
#[serde_as(as = "DisplayFromStr")]
iat: u64,
/// Token expiry date.
/// Дата окончания действия токена
#[serde_as(as = "DisplayFromStr")]
exp: u64,
}
/// Token signing algorithm.
/// Алгоритм подписи токенов
pub(crate) const DEFAULT_ALGORITHM: Algorithm = Algorithm::HS256;
/// Checking the token and extracting the UUID of the user account from it.
/// Проверка токена и извлечение из него UUID аккаунта пользователя
pub fn verify_and_decode(token: &String) -> Result<String, Error> {
let mut validation = Validation::new(DEFAULT_ALGORITHM);
@@ -87,7 +87,7 @@ pub fn verify_and_decode(token: &String) -> Result<String, Error> {
}
}
/// Creating a user token.
/// Создание токена пользователя
pub fn encode(id: &String) -> String {
let header = Header {
typ: Some(String::from("JWT")),
@@ -132,7 +132,6 @@ mod tests {
);
}
//noinspection SpellCheckingInspection
#[test]
fn test_decode_invalid_signature() {
test_env();
@@ -144,7 +143,6 @@ mod tests {
assert_eq!(result.err().unwrap(), Error::InvalidSignature);
}
//noinspection SpellCheckingInspection
#[test]
fn test_decode_expired() {
test_env();
@@ -156,7 +154,6 @@ mod tests {
assert_eq!(result.err().unwrap(), Error::Expired);
}
//noinspection SpellCheckingInspection
#[test]
fn test_decode_ok() {
test_env();

View File

@@ -1,4 +1,3 @@
pub mod jwt;
pub mod error;
pub mod hasher;
pub mod mutex;
pub mod hasher;

View File

@@ -1,77 +0,0 @@
use std::ops::DerefMut;
use std::sync::Mutex;
pub trait MutexScope<T, ScopeFn, ScopeFnOutput>
where
ScopeFn: FnOnce(&mut T) -> ScopeFnOutput,
{
/// Replaces manually creating a mutex lock to perform operations on the data it manages.
///
/// # Arguments
///
/// * `f`: Function (mostly lambda) to which a reference to the mutable object stored in the mutex will be passed.
///
/// returns: Return value of `f` function.
///
/// # Examples
///
/// ```
/// let mtx: Mutex<i32> = Mutex::new(10);
///
/// let res = mtx.scope(|x| { *x = *x * 2; *x });
/// assert_eq!(res, *mtx.lock().unwrap());
/// ```
fn scope(&self, f: ScopeFn) -> ScopeFnOutput;
}
impl<T, ScopeFn, ScopeFnOutput> MutexScope<T, ScopeFn, ScopeFnOutput> for Mutex<T>
where
ScopeFn: FnOnce(&mut T) -> ScopeFnOutput,
{
fn scope(&self, f: ScopeFn) -> ScopeFnOutput {
let mut lock = self.lock().unwrap();
let inner = lock.deref_mut();
f(inner)
}
}
pub trait MutexScopeAsync<T> {
/// ## Asynchronous variant of [MutexScope::scope][MutexScope::scope].
///
/// Replaces manually creating a mutex lock to perform operations on the data it manages.
///
/// # Arguments
///
/// * `f`: Asynchronous function (mostly lambda) to which a reference to the mutable object stored in the mutex will be passed.
///
/// returns: Return value of `f` function.
///
/// # Examples
///
/// ```
/// let mtx: Mutex<i32> = Mutex::new(10);
///
/// let res = mtx.async_scope(async |x| { *x = *x * 2; *x }).await;
/// assert_eq!(res, *mtx.lock().unwrap());
/// ```
async fn async_scope<'a, F, FnFut, FnOut>(&'a self, f: F) -> FnOut
where
FnFut: Future<Output = FnOut>,
F: FnOnce(&'a mut T) -> FnFut,
T: 'a;
}
impl<T> MutexScopeAsync<T> for Mutex<T> {
async fn async_scope<'a, F, FnFut, FnOut>(&'a self, f: F) -> FnOut
where
FnFut: Future<Output = FnOut>,
F: FnOnce(&'a mut T) -> FnFut,
T: 'a,
{
let mut guard = self.lock().unwrap();
let ptr: &'a mut T = unsafe { &mut *(guard.deref_mut() as *mut _) };
f(ptr).await
}
}

View File

@@ -1,13 +1,11 @@
use crate::xls_downloader::interface::{FetchError, FetchOk, FetchResult, XLSDownloader};
use chrono::{DateTime, Utc};
use std::env;
pub struct BasicXlsDownloader {
pub url: Option<String>,
user_agent: String,
}
async fn fetch_specified(url: &String, user_agent: &String, head: bool) -> FetchResult {
async fn fetch_specified(url: &String, user_agent: String, head: bool) -> FetchResult {
let client = reqwest::Client::new();
let response = if head {
@@ -15,7 +13,7 @@ async fn fetch_specified(url: &String, user_agent: &String, head: bool) -> Fetch
} else {
client.get(url)
}
.header("User-Agent", user_agent.clone())
.header("User-Agent", user_agent)
.send()
.await;
@@ -51,16 +49,13 @@ async fn fetch_specified(url: &String, user_agent: &String, head: bool) -> Fetch
})
}
}
Err(e) => Err(FetchError::Unknown(e)),
Err(_) => Err(FetchError::Unknown),
}
}
impl BasicXlsDownloader {
pub fn new() -> Self {
BasicXlsDownloader {
url: None,
user_agent: env::var("REQWEST_USER_AGENT").expect("USER_AGENT must be set"),
}
BasicXlsDownloader { url: None }
}
}
@@ -69,12 +64,17 @@ impl XLSDownloader for BasicXlsDownloader {
if self.url.is_none() {
Err(FetchError::NoUrlProvided)
} else {
fetch_specified(self.url.as_ref().unwrap(), &self.user_agent, head).await
fetch_specified(
self.url.as_ref().unwrap(),
"t.me/polytechnic_next".to_string(),
head,
)
.await
}
}
async fn set_url(&mut self, url: String) -> FetchResult {
let result = fetch_specified(&url, &self.user_agent, true).await;
let result = fetch_specified(&url, "t.me/polytechnic_next".to_string(), true).await;
if let Ok(_) = result {
self.url = Some(url);
@@ -95,8 +95,8 @@ mod tests {
let user_agent = String::new();
let results = [
fetch_specified(&url, &user_agent, true).await,
fetch_specified(&url, &user_agent, false).await,
fetch_specified(&url, user_agent.clone(), true).await,
fetch_specified(&url, user_agent.clone(), false).await,
];
assert!(results[0].is_err());
@@ -109,8 +109,8 @@ mod tests {
let user_agent = String::new();
let results = [
fetch_specified(&url, &user_agent, true).await,
fetch_specified(&url, &user_agent, false).await,
fetch_specified(&url, user_agent.clone(), true).await,
fetch_specified(&url, user_agent.clone(), false).await,
];
assert!(results[0].is_err());
@@ -132,8 +132,8 @@ mod tests {
let user_agent = String::new();
let results = [
fetch_specified(&url, &user_agent, true).await,
fetch_specified(&url, &user_agent, false).await,
fetch_specified(&url, user_agent.clone(), true).await,
fetch_specified(&url, user_agent.clone(), false).await,
];
assert!(results[0].is_err());
@@ -149,8 +149,8 @@ mod tests {
let user_agent = String::new();
let results = [
fetch_specified(&url, &user_agent, true).await,
fetch_specified(&url, &user_agent, false).await,
fetch_specified(&url, user_agent.clone(), true).await,
fetch_specified(&url, user_agent.clone(), false).await,
];
assert!(results[0].is_err());
@@ -172,8 +172,8 @@ mod tests {
let user_agent = String::new();
let results = [
fetch_specified(&url, &user_agent, true).await,
fetch_specified(&url, &user_agent, false).await,
fetch_specified(&url, user_agent.clone(), true).await,
fetch_specified(&url, user_agent.clone(), false).await,
];
assert!(results[0].is_ok());

View File

@@ -1,48 +1,41 @@
use chrono::{DateTime, Utc};
use std::mem::discriminant;
/// XLS data retrieval errors.
#[derive(Debug)]
/// Ошибки получения данных XLS
#[derive(PartialEq, Debug)]
pub enum FetchError {
/// File url is not set.
/// Не установлена ссылка на файл
NoUrlProvided,
/// Unknown error.
Unknown(reqwest::Error),
/// Неизвестная ошибка
Unknown,
/// Server returned a status code different from 200.
/// Сервер вернул статус код отличающийся от 200
BadStatusCode,
/// The url leads to a file of a different type.
/// Ссылка ведёт на файл другого типа
BadContentType,
/// Server doesn't return expected headers.
/// Сервер не вернул ожидаемые заголовки
BadHeaders,
}
impl PartialEq for FetchError {
fn eq(&self, other: &Self) -> bool {
discriminant(self) == discriminant(other)
}
}
/// Result of XLS data retrieval.
/// Результат получения данных XLS
pub struct FetchOk {
/// ETag object.
/// ETag объекта
pub etag: String,
/// File upload date.
/// Дата загрузки файла
pub uploaded_at: DateTime<Utc>,
/// Date data received.
/// Дата получения данных
pub requested_at: DateTime<Utc>,
/// File data.
/// Данные файла
pub data: Option<Vec<u8>>,
}
impl FetchOk {
/// Result without file content.
/// Результат без контента файла
pub fn head(etag: String, uploaded_at: DateTime<Utc>) -> Self {
FetchOk {
etag,
@@ -52,7 +45,7 @@ impl FetchOk {
}
}
/// Full result.
/// Полный результат
pub fn get(etag: String, uploaded_at: DateTime<Utc>, data: Vec<u8>) -> Self {
FetchOk {
etag,
@@ -66,9 +59,9 @@ impl FetchOk {
pub type FetchResult = Result<FetchOk, FetchError>;
pub trait XLSDownloader {
/// Get data about the file, and optionally its content.
/// Получение данных о файле, и, опционально, его контент
async fn fetch(&self, head: bool) -> FetchResult;
/// Setting the file link.
/// Установка ссылки на файл
async fn set_url(&mut self, url: String) -> FetchResult;
}