mirror of
https://github.com/n08i40k/schedule-parser-rusted.git
synced 2025-12-06 17:57:47 +03:00
Compare commits
20 Commits
5b6f5c830f
...
release/v1
| Author | SHA1 | Date | |
|---|---|---|---|
|
4c738085f2
|
|||
|
20602eb863
|
|||
|
e04d462223
|
|||
|
22af02464d
|
|||
|
9a517519db
|
|||
|
65376e75f7
|
|||
|
bef6163c1b
|
|||
|
283858fea3
|
|||
|
66ad4ef938
|
|||
|
28f59389ed
|
|||
|
e71ab0526d
|
|||
|
ff05614404
|
|||
|
9cc03c4ffe
|
|||
|
5068fe3069
|
|||
|
2fd6d787a0
|
|||
|
7a1b32d843
|
|||
|
542258df01
|
|||
|
ccaabfe909
|
|||
|
4c5e0761eb
|
|||
|
057dac5b09
|
169
.github/workflows/release.yml
vendored
Normal file
169
.github/workflows/release.yml
vendored
Normal file
@@ -0,0 +1,169 @@
|
|||||||
|
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
|
||||||
6
.github/workflows/test.yml
vendored
6
.github/workflows/test.yml
vendored
@@ -1,10 +1,9 @@
|
|||||||
name: Tests
|
name: cargo test
|
||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: [ "master" ]
|
branches: [ "master" ]
|
||||||
pull_request:
|
tags-ignore: [ "release/v*" ]
|
||||||
branches: [ "master" ]
|
|
||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
@@ -30,3 +29,4 @@ jobs:
|
|||||||
JWT_SECRET: "test-secret-at-least-256-bits-used"
|
JWT_SECRET: "test-secret-at-least-256-bits-used"
|
||||||
VKID_CLIENT_ID: 0
|
VKID_CLIENT_ID: 0
|
||||||
VKID_REDIRECT_URI: "vk0://vk.com/blank.html"
|
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)"
|
||||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -4,3 +4,4 @@ schedule.json
|
|||||||
teachers.json
|
teachers.json
|
||||||
|
|
||||||
.env*
|
.env*
|
||||||
|
/*-firebase-adminsdk-*.json
|
||||||
|
|||||||
1
.idea/schedule-parser-rusted.iml
generated
1
.idea/schedule-parser-rusted.iml
generated
@@ -10,6 +10,7 @@
|
|||||||
<excludeFolder url="file://$MODULE_DIR$/actix-macros/target" />
|
<excludeFolder url="file://$MODULE_DIR$/actix-macros/target" />
|
||||||
<excludeFolder url="file://$MODULE_DIR$/actix-test/target" />
|
<excludeFolder url="file://$MODULE_DIR$/actix-test/target" />
|
||||||
<excludeFolder url="file://$MODULE_DIR$/target" />
|
<excludeFolder url="file://$MODULE_DIR$/target" />
|
||||||
|
<excludeFolder url="file://$MODULE_DIR$/.idea/dataSources" />
|
||||||
</content>
|
</content>
|
||||||
<orderEntry type="inheritedJdk" />
|
<orderEntry type="inheritedJdk" />
|
||||||
<orderEntry type="sourceFolder" forTests="false" />
|
<orderEntry type="sourceFolder" forTests="false" />
|
||||||
|
|||||||
9
.idea/sqldialects.xml
generated
9
.idea/sqldialects.xml
generated
@@ -1,9 +0,0 @@
|
|||||||
<?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>
|
|
||||||
986
Cargo.lock
generated
986
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -3,10 +3,13 @@ members = ["actix-macros", "actix-test"]
|
|||||||
|
|
||||||
[package]
|
[package]
|
||||||
name = "schedule-parser-rusted"
|
name = "schedule-parser-rusted"
|
||||||
version = "0.8.0"
|
version = "1.0.2"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
publish = false
|
publish = false
|
||||||
|
|
||||||
|
[profile.release]
|
||||||
|
debug = true
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-web = "4.10.2"
|
actix-web = "4.10.2"
|
||||||
actix-macros = { path = "actix-macros" }
|
actix-macros = { path = "actix-macros" }
|
||||||
@@ -18,6 +21,7 @@ diesel = { version = "2.2.8", features = ["postgres"] }
|
|||||||
diesel-derive-enum = { git = "https://github.com/Havunen/diesel-derive-enum.git", features = ["postgres"] }
|
diesel-derive-enum = { git = "https://github.com/Havunen/diesel-derive-enum.git", features = ["postgres"] }
|
||||||
dotenvy = "0.15.7"
|
dotenvy = "0.15.7"
|
||||||
env_logger = "0.11.7"
|
env_logger = "0.11.7"
|
||||||
|
firebase-messaging-rs = { git = "https://github.com/i10416/firebase-messaging-rs.git" }
|
||||||
futures-util = "0.3.31"
|
futures-util = "0.3.31"
|
||||||
fuzzy-matcher = "0.3.7"
|
fuzzy-matcher = "0.3.7"
|
||||||
jsonwebtoken = { version = "9.3.1", features = ["use_pem"] }
|
jsonwebtoken = { version = "9.3.1", features = ["use_pem"] }
|
||||||
@@ -26,6 +30,8 @@ mime = "0.3.17"
|
|||||||
objectid = "0.2.0"
|
objectid = "0.2.0"
|
||||||
regex = "1.11.1"
|
regex = "1.11.1"
|
||||||
reqwest = { version = "0.12.15", features = ["json"] }
|
reqwest = { version = "0.12.15", features = ["json"] }
|
||||||
|
sentry = "0.37.0"
|
||||||
|
sentry-actix = "0.37.0"
|
||||||
serde = { version = "1.0.219", features = ["derive"] }
|
serde = { version = "1.0.219", features = ["derive"] }
|
||||||
serde_json = "1.0.140"
|
serde_json = "1.0.140"
|
||||||
serde_with = "3.12.0"
|
serde_with = "3.12.0"
|
||||||
|
|||||||
14
Dockerfile
Normal file
14
Dockerfile
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
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"]
|
||||||
@@ -2,5 +2,5 @@ CREATE TABLE fcm
|
|||||||
(
|
(
|
||||||
user_id text PRIMARY KEY NOT NULL REFERENCES users (id),
|
user_id text PRIMARY KEY NOT NULL REFERENCES users (id),
|
||||||
token text NOT NULL,
|
token text NOT NULL,
|
||||||
topics text[] NOT NULL
|
topics text[] NOT NULL CHECK ( array_position(topics, null) is null )
|
||||||
);
|
);
|
||||||
@@ -4,11 +4,11 @@ use crate::xls_downloader::basic_impl::BasicXlsDownloader;
|
|||||||
use actix_web::web;
|
use actix_web::web;
|
||||||
use chrono::{DateTime, Utc};
|
use chrono::{DateTime, Utc};
|
||||||
use diesel::{Connection, PgConnection};
|
use diesel::{Connection, PgConnection};
|
||||||
|
use firebase_messaging_rs::FCMClient;
|
||||||
use sha1::{Digest, Sha1};
|
use sha1::{Digest, Sha1};
|
||||||
use std::env;
|
use std::env;
|
||||||
use std::hash::Hash;
|
use std::hash::Hash;
|
||||||
use std::ops::DerefMut;
|
use std::sync::Mutex;
|
||||||
use std::sync::{Mutex, MutexGuard};
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct Schedule {
|
pub struct Schedule {
|
||||||
@@ -50,16 +50,17 @@ impl Schedule {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Общие данные передаваемые в эндпоинты
|
/// Common data provided to endpoints.
|
||||||
pub struct AppState {
|
pub struct AppState {
|
||||||
pub downloader: Mutex<BasicXlsDownloader>,
|
pub downloader: Mutex<BasicXlsDownloader>,
|
||||||
pub schedule: Mutex<Option<Schedule>>,
|
pub schedule: Mutex<Option<Schedule>>,
|
||||||
pub database: Mutex<PgConnection>,
|
pub database: Mutex<PgConnection>,
|
||||||
pub vk_id: VkId,
|
pub vk_id: VkId,
|
||||||
|
pub fcm_client: Option<Mutex<FCMClient>>, // в рантайме не меняется, так что опционален мьютекс, а не данные в нём.
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AppState {
|
impl AppState {
|
||||||
pub fn new() -> Self {
|
pub async fn new() -> Self {
|
||||||
let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
|
let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
@@ -70,28 +71,18 @@ impl AppState {
|
|||||||
.unwrap_or_else(|_| panic!("Error connecting to {}", database_url)),
|
.unwrap_or_else(|_| panic!("Error connecting to {}", database_url)),
|
||||||
),
|
),
|
||||||
vk_id: VkId::new(),
|
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
|
||||||
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AppState {
|
/// Create a new object web::Data<AppState>.
|
||||||
/// Получение объекта соединения с базой данных PostgreSQL
|
pub async fn app_state() -> web::Data<AppState> {
|
||||||
pub fn connection(&self) -> MutexGuard<PgConnection> {
|
web::Data::new(AppState::new().await)
|
||||||
self.database.lock().unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn lock_connection<T, F>(&self, f: F) -> T
|
|
||||||
where
|
|
||||||
F: FnOnce(&mut PgConnection) -> T,
|
|
||||||
{
|
|
||||||
let mut lock = self.connection();
|
|
||||||
let conn = lock.deref_mut();
|
|
||||||
|
|
||||||
f(conn)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Создание нового объекта web::Data<AppState>
|
|
||||||
pub fn app_state() -> web::Data<AppState> {
|
|
||||||
web::Data::new(AppState::new())
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,118 +1,163 @@
|
|||||||
pub mod users {
|
pub mod users {
|
||||||
|
use crate::app_state::AppState;
|
||||||
use crate::database::models::User;
|
use crate::database::models::User;
|
||||||
use crate::database::schema::users::dsl::users;
|
use crate::database::schema::users::dsl::users;
|
||||||
use crate::database::schema::users::dsl::*;
|
use crate::database::schema::users::dsl::*;
|
||||||
use diesel::{insert_into, ExpressionMethods, QueryResult};
|
use crate::utility::mutex::MutexScope;
|
||||||
use diesel::{PgConnection, SelectableHelper};
|
use actix_web::web;
|
||||||
|
use diesel::{ExpressionMethods, QueryResult, insert_into};
|
||||||
use diesel::{QueryDsl, RunQueryDsl};
|
use diesel::{QueryDsl, RunQueryDsl};
|
||||||
use std::ops::DerefMut;
|
use diesel::{SaveChangesDsl, SelectableHelper};
|
||||||
use std::sync::Mutex;
|
|
||||||
|
|
||||||
pub fn get(connection: &Mutex<PgConnection>, _id: &String) -> QueryResult<User> {
|
|
||||||
let mut lock = connection.lock().unwrap();
|
|
||||||
let con = lock.deref_mut();
|
|
||||||
|
|
||||||
|
pub fn get(state: &web::Data<AppState>, _id: &String) -> QueryResult<User> {
|
||||||
|
state.database.scope(|conn| {
|
||||||
users
|
users
|
||||||
.filter(id.eq(_id))
|
.filter(id.eq(_id))
|
||||||
.select(User::as_select())
|
.select(User::as_select())
|
||||||
.first(con)
|
.first(conn)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_by_username(
|
pub fn get_by_username(state: &web::Data<AppState>, _username: &String) -> QueryResult<User> {
|
||||||
connection: &Mutex<PgConnection>,
|
state.database.scope(|conn| {
|
||||||
_username: &String,
|
|
||||||
) -> QueryResult<User> {
|
|
||||||
let mut lock = connection.lock().unwrap();
|
|
||||||
let con = lock.deref_mut();
|
|
||||||
|
|
||||||
users
|
users
|
||||||
.filter(username.eq(_username))
|
.filter(username.eq(_username))
|
||||||
.select(User::as_select())
|
.select(User::as_select())
|
||||||
.first(con)
|
.first(conn)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_by_vk_id(connection: &Mutex<PgConnection>, _vk_id: i32) -> QueryResult<User> {
|
//noinspection RsTraitObligations
|
||||||
let mut lock = connection.lock().unwrap();
|
pub fn get_by_vk_id(state: &web::Data<AppState>, _vk_id: i32) -> QueryResult<User> {
|
||||||
let con = lock.deref_mut();
|
state.database.scope(|conn| {
|
||||||
|
|
||||||
users
|
users
|
||||||
.filter(vk_id.eq(_vk_id))
|
.filter(vk_id.eq(_vk_id))
|
||||||
.select(User::as_select())
|
.select(User::as_select())
|
||||||
.first(con)
|
.first(conn)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn contains_by_username(connection: &Mutex<PgConnection>, _username: &String) -> bool {
|
//noinspection DuplicatedCode
|
||||||
let mut lock = connection.lock().unwrap();
|
pub fn contains_by_username(state: &web::Data<AppState>, _username: &String) -> bool {
|
||||||
let con = lock.deref_mut();
|
// и как это нахуй сократить блять примеров нихуя нет, нихуя не работает
|
||||||
|
// как меня этот раст заебал уже
|
||||||
|
state.database.scope(|conn| {
|
||||||
match users
|
match users
|
||||||
.filter(username.eq(_username))
|
.filter(username.eq(_username))
|
||||||
.count()
|
.count()
|
||||||
.get_result::<i64>(con)
|
.get_result::<i64>(conn)
|
||||||
{
|
{
|
||||||
Ok(count) => count > 0,
|
Ok(count) => count > 0,
|
||||||
Err(_) => false,
|
Err(_) => false,
|
||||||
}
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn contains_by_vk_id(connection: &Mutex<PgConnection>, _vk_id: i32) -> bool {
|
//noinspection DuplicatedCode
|
||||||
let mut lock = connection.lock().unwrap();
|
//noinspection RsTraitObligations
|
||||||
let con = lock.deref_mut();
|
pub fn contains_by_vk_id(state: &web::Data<AppState>, _vk_id: i32) -> bool {
|
||||||
|
state.database.scope(|conn| {
|
||||||
match users
|
match users
|
||||||
.filter(vk_id.eq(_vk_id))
|
.filter(vk_id.eq(_vk_id))
|
||||||
.count()
|
.count()
|
||||||
.get_result::<i64>(con)
|
.get_result::<i64>(conn)
|
||||||
{
|
{
|
||||||
Ok(count) => count > 0,
|
Ok(count) => count > 0,
|
||||||
Err(_) => false,
|
Err(_) => false,
|
||||||
}
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn insert(connection: &Mutex<PgConnection>, user: &User) -> QueryResult<usize> {
|
pub fn insert(state: &web::Data<AppState>, user: &User) -> QueryResult<usize> {
|
||||||
let mut lock = connection.lock().unwrap();
|
state
|
||||||
let con = lock.deref_mut();
|
.database
|
||||||
|
.scope(|conn| insert_into(users).values(user).execute(conn))
|
||||||
|
}
|
||||||
|
|
||||||
insert_into(users).values(user).execute(con)
|
/// 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))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
pub fn delete_by_username(connection: &Mutex<PgConnection>, _username: &String) -> bool {
|
pub fn delete_by_username(state: &web::Data<AppState>, _username: &String) -> bool {
|
||||||
let mut lock = connection.lock().unwrap();
|
state.database.scope(|conn| {
|
||||||
let con = lock.deref_mut();
|
match diesel::delete(users.filter(username.eq(_username))).execute(conn) {
|
||||||
|
|
||||||
match diesel::delete(users.filter(username.eq(_username))).execute(con) {
|
|
||||||
Ok(count) => count > 0,
|
Ok(count) => count > 0,
|
||||||
Err(_) => false,
|
Err(_) => false,
|
||||||
}
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
pub fn insert_or_ignore(connection: &Mutex<PgConnection>, user: &User) -> QueryResult<usize> {
|
pub fn insert_or_ignore(state: &web::Data<AppState>, user: &User) -> QueryResult<usize> {
|
||||||
let mut lock = connection.lock().unwrap();
|
state.database.scope(|conn| {
|
||||||
let con = lock.deref_mut();
|
|
||||||
|
|
||||||
insert_into(users)
|
insert_into(users)
|
||||||
.values(user)
|
.values(user)
|
||||||
.on_conflict_do_nothing()
|
.on_conflict_do_nothing()
|
||||||
.execute(con)
|
.execute(conn)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub mod fcm {
|
pub mod fcm {
|
||||||
use crate::database::models::{User, 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::QueryDsl;
|
||||||
use diesel::RunQueryDsl;
|
use diesel::RunQueryDsl;
|
||||||
use diesel::{BelongingToDsl, PgConnection, QueryResult, SelectableHelper};
|
use diesel::{BelongingToDsl, QueryResult, SelectableHelper};
|
||||||
use std::ops::DerefMut;
|
|
||||||
use std::sync::Mutex;
|
|
||||||
|
|
||||||
pub fn from_user(connection: &Mutex<PgConnection>, user: &User) -> QueryResult<FCM> {
|
|
||||||
let mut lock = connection.lock().unwrap();
|
|
||||||
let con = lock.deref_mut();
|
|
||||||
|
|
||||||
|
pub fn from_user(state: &web::Data<AppState>, user: &User) -> QueryResult<FCM> {
|
||||||
|
state.database.scope(|conn| {
|
||||||
FCM::belonging_to(&user)
|
FCM::belonging_to(&user)
|
||||||
.select(FCM::as_select())
|
.select(FCM::as_select())
|
||||||
.get_result(con)
|
.get_result(conn)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,33 +31,34 @@ pub enum UserRole {
|
|||||||
#[diesel(table_name = crate::database::schema::users)]
|
#[diesel(table_name = crate::database::schema::users)]
|
||||||
#[diesel(treat_none_as_null = true)]
|
#[diesel(treat_none_as_null = true)]
|
||||||
pub struct User {
|
pub struct User {
|
||||||
/// UUID аккаунта
|
/// Account UUID.
|
||||||
pub id: String,
|
pub id: String,
|
||||||
|
|
||||||
/// Имя пользователя
|
/// User name.
|
||||||
pub username: String,
|
pub username: String,
|
||||||
|
|
||||||
/// BCrypt хеш пароля
|
/// BCrypt password hash.
|
||||||
pub password: String,
|
pub password: String,
|
||||||
|
|
||||||
/// Идентификатор привязанного аккаунта VK
|
/// ID of the linked VK account.
|
||||||
pub vk_id: Option<i32>,
|
pub vk_id: Option<i32>,
|
||||||
|
|
||||||
/// JWT токен доступа
|
/// JWT access token.
|
||||||
pub access_token: String,
|
pub access_token: String,
|
||||||
|
|
||||||
/// Группа
|
/// Group.
|
||||||
pub group: String,
|
pub group: String,
|
||||||
|
|
||||||
/// Роль
|
/// Role.
|
||||||
pub role: UserRole,
|
pub role: UserRole,
|
||||||
|
|
||||||
/// Версия установленного приложения Polytechnic+
|
/// Version of the installed Polytechnic+ application.
|
||||||
pub version: String,
|
pub version: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(
|
#[derive(
|
||||||
Debug,
|
Debug,
|
||||||
|
Clone,
|
||||||
Serialize,
|
Serialize,
|
||||||
Identifiable,
|
Identifiable,
|
||||||
Queryable,
|
Queryable,
|
||||||
@@ -72,12 +73,12 @@ pub struct User {
|
|||||||
#[diesel(table_name = crate::database::schema::fcm)]
|
#[diesel(table_name = crate::database::schema::fcm)]
|
||||||
#[diesel(primary_key(user_id))]
|
#[diesel(primary_key(user_id))]
|
||||||
pub struct FCM {
|
pub struct FCM {
|
||||||
/// UUID аккаунта.
|
/// Account UUID.
|
||||||
pub user_id: String,
|
pub user_id: String,
|
||||||
|
|
||||||
/// FCM токен.
|
/// FCM token.
|
||||||
pub token: String,
|
pub token: String,
|
||||||
|
|
||||||
/// Список топиков, на которые подписан пользователь.
|
/// List of topics subscribed to by the user.
|
||||||
pub topics: Vec<Option<String>>,
|
pub topics: Vec<Option<String>>,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,19 +16,19 @@ use std::fmt::Debug;
|
|||||||
#[status_code = "actix_web::http::StatusCode::UNAUTHORIZED"]
|
#[status_code = "actix_web::http::StatusCode::UNAUTHORIZED"]
|
||||||
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
|
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
|
||||||
pub enum Error {
|
pub enum Error {
|
||||||
/// В запросе отсутствует заголовок Authorization
|
/// There is no Authorization header in the request.
|
||||||
#[display("No Authorization header found")]
|
#[display("No Authorization header found")]
|
||||||
NoHeader,
|
NoHeader,
|
||||||
|
|
||||||
/// Неизвестный тип авторизации, отличающийся от Bearer
|
/// Unknown authorization type other than Bearer.
|
||||||
#[display("Bearer token is required")]
|
#[display("Bearer token is required")]
|
||||||
UnknownAuthorizationType,
|
UnknownAuthorizationType,
|
||||||
|
|
||||||
/// Токен не действителен
|
/// Invalid or expired access token.
|
||||||
#[display("Invalid or expired access token")]
|
#[display("Invalid or expired access token")]
|
||||||
InvalidAccessToken,
|
InvalidAccessToken,
|
||||||
|
|
||||||
/// Пользователь привязанный к токену не найден в базе данных
|
/// The user bound to the token is not found in the database.
|
||||||
#[display("No user associated with access token")]
|
#[display("No user associated with access token")]
|
||||||
NoUser,
|
NoUser,
|
||||||
}
|
}
|
||||||
@@ -39,7 +39,7 @@ impl Error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Экстрактор пользователя из запроса с токеном
|
/// User extractor from request with Bearer access token.
|
||||||
impl FromRequestSync for User {
|
impl FromRequestSync for User {
|
||||||
type Error = actix_web::Error;
|
type Error = actix_web::Error;
|
||||||
|
|
||||||
@@ -63,7 +63,7 @@ impl FromRequestSync for User {
|
|||||||
|
|
||||||
let app_state = req.app_data::<web::Data<AppState>>().unwrap();
|
let app_state = req.app_data::<web::Data<AppState>>().unwrap();
|
||||||
|
|
||||||
driver::users::get(&app_state.database, &user_id).map_err(|_| Error::NoUser.into())
|
driver::users::get(&app_state, &user_id).map_err(|_| Error::NoUser.into())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -87,7 +87,7 @@ impl<const FCM: bool> UserExtractor<{ FCM }> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Экстрактор пользователя и дополнительных параметров из запроса с токеном
|
/// Extractor of user and additional parameters from request with Bearer token.
|
||||||
impl<const FCM: bool> FromRequestSync for UserExtractor<{ FCM }> {
|
impl<const FCM: bool> FromRequestSync for UserExtractor<{ FCM }> {
|
||||||
type Error = actix_web::Error;
|
type Error = actix_web::Error;
|
||||||
|
|
||||||
@@ -100,7 +100,7 @@ impl<const FCM: bool> FromRequestSync for UserExtractor<{ FCM }> {
|
|||||||
|
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
fcm: if FCM {
|
fcm: if FCM {
|
||||||
driver::fcm::from_user(&app_state.database, &user).ok()
|
driver::fcm::from_user(&app_state, &user).ok()
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -2,26 +2,64 @@ use actix_web::dev::Payload;
|
|||||||
use actix_web::{FromRequest, HttpRequest};
|
use actix_web::{FromRequest, HttpRequest};
|
||||||
use futures_util::future::LocalBoxFuture;
|
use futures_util::future::LocalBoxFuture;
|
||||||
use std::future::{Ready, ready};
|
use std::future::{Ready, ready};
|
||||||
|
use std::ops;
|
||||||
|
|
||||||
/// Асинхронный экстрактор объектов из запроса
|
/// # Async extractor.
|
||||||
|
|
||||||
|
/// Asynchronous object extractor from a query.
|
||||||
pub struct AsyncExtractor<T>(T);
|
pub struct AsyncExtractor<T>(T);
|
||||||
|
|
||||||
impl<T> AsyncExtractor<T> {
|
impl<T> AsyncExtractor<T> {
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
/// Получение объекта, извлечённого с помощью экстрактора
|
/// Retrieve the object extracted with the extractor.
|
||||||
pub fn into_inner(self) -> T {
|
pub fn into_inner(self) -> T {
|
||||||
self.0
|
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 {
|
pub trait FromRequestAsync: Sized {
|
||||||
type Error: Into<actix_web::Error>;
|
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>;
|
async fn from_request_async(req: HttpRequest, payload: Payload) -> Result<Self, Self::Error>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Реализация треита FromRequest для всех асинхронных экстракторов
|
|
||||||
impl<T: FromRequestAsync> FromRequest for AsyncExtractor<T> {
|
impl<T: FromRequestAsync> FromRequest for AsyncExtractor<T> {
|
||||||
type Error = T::Error;
|
type Error = T::Error;
|
||||||
type Future = LocalBoxFuture<'static, Result<Self, Self::Error>>;
|
type Future = LocalBoxFuture<'static, Result<Self, Self::Error>>;
|
||||||
@@ -37,24 +75,72 @@ impl<T: FromRequestAsync> FromRequest for AsyncExtractor<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Синхронный экстрактор объектов из запроса
|
/// # Sync extractor.
|
||||||
|
|
||||||
|
/// Synchronous object extractor from a query.
|
||||||
pub struct SyncExtractor<T>(T);
|
pub struct SyncExtractor<T>(T);
|
||||||
|
|
||||||
impl<T> SyncExtractor<T> {
|
impl<T> SyncExtractor<T> {
|
||||||
/// Получение объекта, извлечённого с помощью экстрактора
|
/// Retrieving an object extracted with the extractor.
|
||||||
pub fn into_inner(self) -> T {
|
pub fn into_inner(self) -> T {
|
||||||
self.0
|
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 {
|
pub trait FromRequestSync: Sized {
|
||||||
type Error: Into<actix_web::Error>;
|
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>;
|
fn from_request_sync(req: &HttpRequest, payload: &mut Payload) -> Result<Self, Self::Error>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Реализация треита FromRequest для всех синхронных экстракторов
|
|
||||||
impl<T: FromRequestSync> FromRequest for SyncExtractor<T> {
|
impl<T: FromRequestSync> FromRequest for SyncExtractor<T> {
|
||||||
type Error = T::Error;
|
type Error = T::Error;
|
||||||
type Future = Ready<Result<Self, Self::Error>>;
|
type Future = Ready<Result<Self, Self::Error>>;
|
||||||
|
|||||||
56
src/main.rs
56
src/main.rs
@@ -1,8 +1,10 @@
|
|||||||
use crate::app_state::{AppState, app_state};
|
use crate::app_state::{AppState, app_state};
|
||||||
use crate::middlewares::authorization::JWTAuthorization;
|
use crate::middlewares::authorization::JWTAuthorization;
|
||||||
|
use crate::middlewares::content_type::ContentTypeBootstrap;
|
||||||
use actix_web::dev::{ServiceFactory, ServiceRequest};
|
use actix_web::dev::{ServiceFactory, ServiceRequest};
|
||||||
use actix_web::{App, Error, HttpServer};
|
use actix_web::{App, Error, HttpServer};
|
||||||
use dotenvy::dotenv;
|
use dotenvy::dotenv;
|
||||||
|
use std::io;
|
||||||
use utoipa_actix_web::AppExt;
|
use utoipa_actix_web::AppExt;
|
||||||
use utoipa_actix_web::scope::Scope;
|
use utoipa_actix_web::scope::Scope;
|
||||||
use utoipa_rapidoc::RapiDoc;
|
use utoipa_rapidoc::RapiDoc;
|
||||||
@@ -35,11 +37,15 @@ pub fn get_api_scope<
|
|||||||
.service(routes::auth::sign_up_vk);
|
.service(routes::auth::sign_up_vk);
|
||||||
|
|
||||||
let users_scope = utoipa_actix_web::scope("/users")
|
let users_scope = utoipa_actix_web::scope("/users")
|
||||||
.wrap(JWTAuthorization)
|
.wrap(JWTAuthorization::default())
|
||||||
|
.service(routes::users::change_group)
|
||||||
|
.service(routes::users::change_username)
|
||||||
.service(routes::users::me);
|
.service(routes::users::me);
|
||||||
|
|
||||||
let schedule_scope = utoipa_actix_web::scope("/schedule")
|
let schedule_scope = utoipa_actix_web::scope("/schedule")
|
||||||
.wrap(JWTAuthorization)
|
.wrap(JWTAuthorization {
|
||||||
|
ignore: &["/group-names", "/teacher-names"],
|
||||||
|
})
|
||||||
.service(routes::schedule::schedule)
|
.service(routes::schedule::schedule)
|
||||||
.service(routes::schedule::update_download_url)
|
.service(routes::schedule::update_download_url)
|
||||||
.service(routes::schedule::cache_status)
|
.service(routes::schedule::cache_status)
|
||||||
@@ -49,8 +55,9 @@ pub fn get_api_scope<
|
|||||||
.service(routes::schedule::teacher_names);
|
.service(routes::schedule::teacher_names);
|
||||||
|
|
||||||
let fcm_scope = utoipa_actix_web::scope("/fcm")
|
let fcm_scope = utoipa_actix_web::scope("/fcm")
|
||||||
.wrap(JWTAuthorization)
|
.wrap(JWTAuthorization::default())
|
||||||
.service(routes::fcm::update_callback);
|
.service(routes::fcm::update_callback)
|
||||||
|
.service(routes::fcm::set_token);
|
||||||
|
|
||||||
let vk_id_scope = utoipa_actix_web::scope("/vkid") //
|
let vk_id_scope = utoipa_actix_web::scope("/vkid") //
|
||||||
.service(routes::vk_id::oauth);
|
.service(routes::vk_id::oauth);
|
||||||
@@ -63,20 +70,20 @@ pub fn get_api_scope<
|
|||||||
.service(vk_id_scope)
|
.service(vk_id_scope)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[actix_web::main]
|
async fn async_main() -> io::Result<()> {
|
||||||
async fn main() {
|
println!("Starting server...");
|
||||||
dotenv().ok();
|
|
||||||
|
|
||||||
unsafe { std::env::set_var("RUST_LOG", "debug") };
|
let app_state = app_state().await;
|
||||||
env_logger::init();
|
|
||||||
|
|
||||||
let app_state = app_state();
|
|
||||||
|
|
||||||
HttpServer::new(move || {
|
HttpServer::new(move || {
|
||||||
let (app, api) = App::new()
|
let (app, api) = App::new()
|
||||||
.into_utoipa_app()
|
.into_utoipa_app()
|
||||||
.app_data(app_state.clone())
|
.app_data(app_state.clone())
|
||||||
.service(get_api_scope("/api/v1"))
|
.service(
|
||||||
|
get_api_scope("/api/v1")
|
||||||
|
.wrap(sentry_actix::Sentry::new())
|
||||||
|
.wrap(ContentTypeBootstrap),
|
||||||
|
)
|
||||||
.split_for_parts();
|
.split_for_parts();
|
||||||
|
|
||||||
let rapidoc_service = RapiDoc::with_openapi("/api-docs-json", api).path("/api-docs");
|
let rapidoc_service = RapiDoc::with_openapi("/api-docs-json", api).path("/api-docs");
|
||||||
@@ -90,9 +97,28 @@ async fn main() {
|
|||||||
app.service(rapidoc_service.custom_html(patched_rapidoc_html))
|
app.service(rapidoc_service.custom_html(patched_rapidoc_html))
|
||||||
})
|
})
|
||||||
.workers(4)
|
.workers(4)
|
||||||
.bind(("0.0.0.0", 8080))
|
.bind(("0.0.0.0", 5050))?
|
||||||
.unwrap()
|
|
||||||
.run()
|
.run()
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
}
|
||||||
|
|
||||||
|
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(())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,8 +7,17 @@ use actix_web::{Error, HttpRequest, ResponseError};
|
|||||||
use futures_util::future::LocalBoxFuture;
|
use futures_util::future::LocalBoxFuture;
|
||||||
use std::future::{Ready, ready};
|
use std::future::{Ready, ready};
|
||||||
|
|
||||||
/// Middleware guard работающий с токенами JWT
|
/// Middleware guard working with JWT tokens.
|
||||||
pub struct JWTAuthorization;
|
pub struct JWTAuthorization {
|
||||||
|
/// List of ignored endpoints.
|
||||||
|
pub ignore: &'static [&'static str],
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for JWTAuthorization {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self { ignore: &[] }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl<S, B> Transform<S, ServiceRequest> for JWTAuthorization
|
impl<S, B> Transform<S, ServiceRequest> for JWTAuthorization
|
||||||
where
|
where
|
||||||
@@ -23,22 +32,27 @@ where
|
|||||||
type Future = Ready<Result<Self::Transform, Self::InitError>>;
|
type Future = Ready<Result<Self::Transform, Self::InitError>>;
|
||||||
|
|
||||||
fn new_transform(&self, service: S) -> Self::Future {
|
fn new_transform(&self, service: S) -> Self::Future {
|
||||||
ready(Ok(JWTAuthorizationMiddleware { service }))
|
ready(Ok(JWTAuthorizationMiddleware {
|
||||||
|
service,
|
||||||
|
ignore: self.ignore,
|
||||||
|
}))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct JWTAuthorizationMiddleware<S> {
|
pub struct JWTAuthorizationMiddleware<S> {
|
||||||
service: S,
|
service: S,
|
||||||
|
/// List of ignored endpoints.
|
||||||
|
ignore: &'static [&'static str],
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Функция для проверки наличия и действительности токена в запросе, а так же существования пользователя к которому он привязан
|
|
||||||
impl<S, B> JWTAuthorizationMiddleware<S>
|
impl<S, B> JWTAuthorizationMiddleware<S>
|
||||||
where
|
where
|
||||||
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
B: 'static,
|
B: 'static,
|
||||||
{
|
{
|
||||||
pub fn check_authorization(
|
/// Checking the validity of the token.
|
||||||
|
fn check_authorization(
|
||||||
&self,
|
&self,
|
||||||
req: &HttpRequest,
|
req: &HttpRequest,
|
||||||
payload: &mut Payload,
|
payload: &mut Payload,
|
||||||
@@ -47,9 +61,25 @@ where
|
|||||||
.map(|_| ())
|
.map(|_| ())
|
||||||
.map_err(|e| e.as_error::<authorized_user::Error>().unwrap().clone())
|
.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;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<S, B> Service<ServiceRequest> for JWTAuthorizationMiddleware<S>
|
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>
|
||||||
where
|
where
|
||||||
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
@@ -62,6 +92,11 @@ where
|
|||||||
forward_ready!(service);
|
forward_ready!(service);
|
||||||
|
|
||||||
fn call(&self, req: ServiceRequest) -> Self::Future {
|
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();
|
let (http_req, mut payload) = req.into_parts();
|
||||||
|
|
||||||
if let Err(err) = self.check_authorization(&http_req, &mut payload) {
|
if let Err(err) = self.check_authorization(&http_req, &mut payload) {
|
||||||
|
|||||||
64
src/middlewares/content_type.rs
Normal file
64
src/middlewares/content_type.rs
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
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())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1 +1,2 @@
|
|||||||
pub mod authorization;
|
pub mod authorization;
|
||||||
|
pub mod content_type;
|
||||||
@@ -1,10 +1,11 @@
|
|||||||
use crate::parser::LessonParseResult::{Lessons, Street};
|
use crate::parser::LessonParseResult::{Lessons, Street};
|
||||||
use crate::parser::schema::LessonType::Break;
|
use crate::parser::schema::LessonType::Break;
|
||||||
use crate::parser::schema::{
|
use crate::parser::schema::{
|
||||||
Day, Lesson, LessonSubGroup, LessonTime, LessonType, ParseError, ParseResult, ScheduleEntry,
|
Day, ErrorCell, ErrorCellPos, Lesson, LessonSubGroup, LessonTime, LessonType, ParseError,
|
||||||
|
ParseResult, ScheduleEntry,
|
||||||
};
|
};
|
||||||
use calamine::{Reader, Xls, open_workbook_from_rs};
|
use calamine::{Reader, Xls, open_workbook_from_rs};
|
||||||
use chrono::{Duration, NaiveDateTime};
|
use chrono::{DateTime, Duration, NaiveDateTime, Utc};
|
||||||
use fuzzy_matcher::FuzzyMatcher;
|
use fuzzy_matcher::FuzzyMatcher;
|
||||||
use fuzzy_matcher::skim::SkimMatcherV2;
|
use fuzzy_matcher::skim::SkimMatcherV2;
|
||||||
use regex::Regex;
|
use regex::Regex;
|
||||||
@@ -14,39 +15,37 @@ use std::sync::LazyLock;
|
|||||||
|
|
||||||
pub mod schema;
|
pub mod schema;
|
||||||
|
|
||||||
/// Данные ячейке хранящей строку
|
/// Data cell storing the line.
|
||||||
struct InternalId {
|
struct InternalId {
|
||||||
/// Индекс строки
|
/// Line index.
|
||||||
row: u32,
|
row: u32,
|
||||||
|
|
||||||
/// Индекс столбца
|
/// Column index.
|
||||||
column: u32,
|
column: u32,
|
||||||
|
|
||||||
/**
|
/// Text in the cell.
|
||||||
* Текст в ячейке
|
|
||||||
*/
|
|
||||||
name: String,
|
name: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Данные о времени проведения пар из второй колонки расписания
|
/// Data on the time of lessons from the second column of the schedule.
|
||||||
struct InternalTime {
|
struct InternalTime {
|
||||||
/// Временной отрезок проведения пары
|
/// Temporary segment of the lesson.
|
||||||
time_range: LessonTime,
|
time_range: LessonTime,
|
||||||
|
|
||||||
/// Тип пары
|
/// Type of lesson.
|
||||||
lesson_type: LessonType,
|
lesson_type: LessonType,
|
||||||
|
|
||||||
/// Индекс пары
|
/// The lesson index.
|
||||||
default_index: Option<u32>,
|
default_index: Option<u32>,
|
||||||
|
|
||||||
/// Рамка ячейки
|
/// The frame of the cell.
|
||||||
xls_range: ((u32, u32), (u32, u32)),
|
xls_range: ((u32, u32), (u32, u32)),
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Сокращение типа рабочего листа
|
/// Working sheet type alias.
|
||||||
type WorkSheet = calamine::Range<calamine::Data>;
|
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> {
|
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)) {
|
let cell_data = if let Some(data) = worksheet.get((row as usize, col as usize)) {
|
||||||
data.to_string()
|
data.to_string()
|
||||||
@@ -58,9 +57,8 @@ fn get_string_from_cell(worksheet: &WorkSheet, row: u32, col: u32) -> Option<Str
|
|||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
|
|
||||||
static NL_RE: LazyLock<Regex, fn() -> Regex> =
|
static NL_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[\n\r]+").unwrap());
|
||||||
LazyLock::new(|| Regex::new(r"[\n\r]+").unwrap());
|
static SP_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\s+").unwrap());
|
||||||
static SP_RE: LazyLock<Regex, fn() -> Regex> = LazyLock::new(|| Regex::new(r"\s+").unwrap());
|
|
||||||
|
|
||||||
let trimmed_data = SP_RE
|
let trimmed_data = SP_RE
|
||||||
.replace_all(&NL_RE.replace_all(&cell_data, " "), " ")
|
.replace_all(&NL_RE.replace_all(&cell_data, " "), " ")
|
||||||
@@ -74,7 +72,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)) {
|
fn get_merge_from_start(worksheet: &WorkSheet, row: u32, column: u32) -> ((u32, u32), (u32, u32)) {
|
||||||
let worksheet_end = worksheet.end().unwrap();
|
let worksheet_end = worksheet.end().unwrap();
|
||||||
|
|
||||||
@@ -109,7 +107,7 @@ fn get_merge_from_start(worksheet: &WorkSheet, row: u32, column: u32) -> ((u32,
|
|||||||
((row, column), (row_end, column_end))
|
((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> {
|
fn parse_skeleton(worksheet: &WorkSheet) -> Result<(Vec<InternalId>, Vec<InternalId>), ParseError> {
|
||||||
let range = &worksheet;
|
let range = &worksheet;
|
||||||
|
|
||||||
@@ -167,19 +165,20 @@ fn parse_skeleton(worksheet: &WorkSheet) -> Result<(Vec<InternalId>, Vec<Interna
|
|||||||
Ok((days, groups))
|
Ok((days, groups))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Результат получения пары из ячейки
|
/// The result of obtaining a lesson from the cell.
|
||||||
enum LessonParseResult {
|
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>),
|
Lessons(Vec<Lesson>),
|
||||||
|
|
||||||
/// Улица на которой находится корпус политехникума
|
/// Street on which the Polytechnic Corps is located.
|
||||||
Street(String),
|
Street(String),
|
||||||
}
|
}
|
||||||
|
|
||||||
trait StringInnerSlice {
|
trait StringInnerSlice {
|
||||||
/// Получения отрезка строки из строки по начальному и конечному индексу
|
/// Obtaining a line from the line on the initial and final index.
|
||||||
fn inner_slice(&self, from: usize, to: usize) -> Self;
|
fn inner_slice(&self, from: usize, to: usize) -> Self;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -192,7 +191,8 @@ impl StringInnerSlice for String {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Получение нестандартного типа пары по названию
|
// noinspection GrazieInspection
|
||||||
|
/// Obtaining a non-standard type of lesson by name.
|
||||||
fn guess_lesson_type(name: &String) -> Option<(String, LessonType)> {
|
fn guess_lesson_type(name: &String) -> Option<(String, LessonType)> {
|
||||||
let map: HashMap<String, LessonType> = HashMap::from([
|
let map: HashMap<String, LessonType> = HashMap::from([
|
||||||
("(консультация)".to_string(), LessonType::Consultation),
|
("(консультация)".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(
|
fn parse_lesson(
|
||||||
worksheet: &WorkSheet,
|
worksheet: &WorkSheet,
|
||||||
day: &mut Day,
|
day: &mut Day,
|
||||||
@@ -252,7 +252,7 @@ fn parse_lesson(
|
|||||||
|
|
||||||
let raw_name = raw_name_opt.unwrap();
|
let raw_name = raw_name_opt.unwrap();
|
||||||
|
|
||||||
static OTHER_STREET_RE: LazyLock<Regex, fn() -> Regex> =
|
static OTHER_STREET_RE: LazyLock<Regex> =
|
||||||
LazyLock::new(|| Regex::new(r"^[А-Я][а-я]+,?\s?[0-9]+$").unwrap());
|
LazyLock::new(|| Regex::new(r"^[А-Я][а-я]+,?\s?[0-9]+$").unwrap());
|
||||||
|
|
||||||
if OTHER_STREET_RE.is_match(&raw_name) {
|
if OTHER_STREET_RE.is_match(&raw_name) {
|
||||||
@@ -275,7 +275,9 @@ fn parse_lesson(
|
|||||||
.filter(|time| time.xls_range.1.0 == cell_range.1.0)
|
.filter(|time| time.xls_range.1.0 == cell_range.1.0)
|
||||||
.collect::<Vec<&InternalTime>>();
|
.collect::<Vec<&InternalTime>>();
|
||||||
|
|
||||||
let end_time = end_time_arr.first().ok_or(ParseError::LessonTimeNotFound)?;
|
let end_time = end_time_arr
|
||||||
|
.first()
|
||||||
|
.ok_or(ParseError::LessonTimeNotFound(ErrorCellPos { row, column }))?;
|
||||||
|
|
||||||
let range: Option<[u8; 2]> = if time.default_index != None {
|
let range: Option<[u8; 2]> = if time.default_index != None {
|
||||||
let default = time.default_index.unwrap() as u8;
|
let default = time.default_index.unwrap() as u8;
|
||||||
@@ -369,7 +371,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> {
|
fn parse_cabinets(worksheet: &WorkSheet, row: u32, column: u32) -> Vec<String> {
|
||||||
let mut cabinets: Vec<String> = Vec::new();
|
let mut cabinets: Vec<String> = Vec::new();
|
||||||
|
|
||||||
@@ -387,16 +389,14 @@ fn parse_cabinets(worksheet: &WorkSheet, row: u32, column: u32) -> Vec<String> {
|
|||||||
cabinets
|
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> {
|
fn parse_name_and_subgroups(name: &String) -> Result<(String, Vec<LessonSubGroup>), ParseError> {
|
||||||
static LESSON_RE: LazyLock<Regex, fn() -> Regex> =
|
static LESSON_RE: LazyLock<Regex> =
|
||||||
LazyLock::new(|| Regex::new(r"(?:[А-Я][а-я]+[А-Я]{2}(?:\([0-9][а-я]+\))?)+$").unwrap());
|
LazyLock::new(|| Regex::new(r"(?:[А-Я][а-я]+[А-Я]{2}(?:\([0-9][а-я]+\))?)+$").unwrap());
|
||||||
static TEACHER_RE: LazyLock<Regex, fn() -> Regex> =
|
static TEACHER_RE: LazyLock<Regex> =
|
||||||
LazyLock::new(|| Regex::new(r"([А-Я][а-я]+)([А-Я])([А-Я])(?:\(([0-9])[а-я]+\))?").unwrap());
|
LazyLock::new(|| Regex::new(r"([А-Я][а-я]+)([А-Я])([А-Я])(?:\(([0-9])[а-я]+\))?").unwrap());
|
||||||
static CLEAN_RE: LazyLock<Regex, fn() -> Regex> =
|
static CLEAN_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[\s.,]+").unwrap());
|
||||||
LazyLock::new(|| Regex::new(r"[\s.,]+").unwrap());
|
static END_CLEAN_RE: LazyLock<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 (teachers, lesson_name) = {
|
||||||
let clean_name = CLEAN_RE.replace_all(&name, "").to_string();
|
let clean_name = CLEAN_RE.replace_all(&name, "").to_string();
|
||||||
@@ -423,14 +423,9 @@ fn parse_name_and_subgroups(name: &String) -> Result<(String, Vec<LessonSubGroup
|
|||||||
|
|
||||||
for captures in teacher_it {
|
for captures in teacher_it {
|
||||||
subgroups.push(LessonSubGroup {
|
subgroups.push(LessonSubGroup {
|
||||||
number: if let Some(capture) = captures.get(4) {
|
number: match captures.get(4) {
|
||||||
capture
|
Some(capture) => capture.as_str().to_string().parse::<u8>().unwrap(),
|
||||||
.as_str()
|
None => 0,
|
||||||
.to_string()
|
|
||||||
.parse::<u8>()
|
|
||||||
.map_err(|_| ParseError::SubgroupIndexParsingFailed)?
|
|
||||||
} else {
|
|
||||||
0
|
|
||||||
},
|
},
|
||||||
cabinet: None,
|
cabinet: None,
|
||||||
teacher: format!(
|
teacher: format!(
|
||||||
@@ -479,7 +474,7 @@ fn parse_name_and_subgroups(name: &String) -> Result<(String, Vec<LessonSubGroup
|
|||||||
Ok((lesson_name, subgroups))
|
Ok((lesson_name, subgroups))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Конвертация списка пар групп в список пар преподавателей
|
/// Conversion of the list of couples of groups in the list of lessons of teachers.
|
||||||
fn convert_groups_to_teachers(
|
fn convert_groups_to_teachers(
|
||||||
groups: &HashMap<String, ScheduleEntry>,
|
groups: &HashMap<String, ScheduleEntry>,
|
||||||
) -> HashMap<String, ScheduleEntry> {
|
) -> HashMap<String, ScheduleEntry> {
|
||||||
@@ -556,7 +551,26 @@ fn convert_groups_to_teachers(
|
|||||||
teachers
|
teachers
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Чтение XLS документа из буфера и преобразование его в готовые к использованию расписания
|
/// 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);
|
||||||
|
/// ```
|
||||||
pub fn parse_xls(buffer: &Vec<u8>) -> Result<ParseResult, ParseError> {
|
pub fn parse_xls(buffer: &Vec<u8>) -> Result<ParseResult, ParseError> {
|
||||||
let cursor = Cursor::new(&buffer);
|
let cursor = Cursor::new(&buffer);
|
||||||
let mut workbook: Xls<_> =
|
let mut workbook: Xls<_> =
|
||||||
@@ -646,10 +660,12 @@ pub fn parse_xls(buffer: &Vec<u8>) -> Result<ParseResult, ParseError> {
|
|||||||
|
|
||||||
// time
|
// time
|
||||||
let time_range = {
|
let time_range = {
|
||||||
static TIME_RE: LazyLock<Regex, fn() -> Regex> =
|
static TIME_RE: LazyLock<Regex> =
|
||||||
LazyLock::new(|| Regex::new(r"(\d+\.\d+)-(\d+\.\d+)").unwrap());
|
LazyLock::new(|| Regex::new(r"(\d+\.\d+)-(\d+\.\d+)").unwrap());
|
||||||
|
|
||||||
let parse_res = TIME_RE.captures(&time).ok_or(ParseError::GlobalTime)?;
|
let parse_res = TIME_RE.captures(&time).ok_or(ParseError::GlobalTime(
|
||||||
|
ErrorCell::new(row, lesson_time_column, time.clone()),
|
||||||
|
))?;
|
||||||
|
|
||||||
let start_match = parse_res.get(1).unwrap().as_str();
|
let start_match = parse_res.get(1).unwrap().as_str();
|
||||||
let start_parts: Vec<&str> = start_match.split(".").collect();
|
let start_parts: Vec<&str> = start_match.split(".").collect();
|
||||||
@@ -657,13 +673,15 @@ pub fn parse_xls(buffer: &Vec<u8>) -> Result<ParseResult, ParseError> {
|
|||||||
let end_match = parse_res.get(2).unwrap().as_str();
|
let end_match = parse_res.get(2).unwrap().as_str();
|
||||||
let end_parts: Vec<&str> = end_match.split(".").collect();
|
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 {
|
LessonTime {
|
||||||
start: day.date.clone()
|
start: GET_TIME(day.date.clone(), &start_parts),
|
||||||
+ Duration::hours(start_parts[0].parse().unwrap())
|
end: GET_TIME(day.date.clone(), &end_parts),
|
||||||
+ 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()),
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,144 +1,165 @@
|
|||||||
use chrono::{DateTime, Utc};
|
use chrono::{DateTime, Utc};
|
||||||
use derive_more::Display;
|
use derive_more::{Display, Error};
|
||||||
use serde::{Deserialize, Serialize, Serializer};
|
use serde::{Deserialize, Serialize, Serializer};
|
||||||
use serde_repr::{Deserialize_repr, Serialize_repr};
|
use serde_repr::{Deserialize_repr, Serialize_repr};
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use utoipa::ToSchema;
|
use utoipa::ToSchema;
|
||||||
|
|
||||||
|
/// The beginning and end of the lesson.
|
||||||
#[derive(Clone, Hash, Debug, Serialize, Deserialize, ToSchema)]
|
#[derive(Clone, Hash, Debug, Serialize, Deserialize, ToSchema)]
|
||||||
pub struct LessonTime {
|
pub struct LessonTime {
|
||||||
/// Начало пары
|
/// The beginning of a lesson.
|
||||||
pub start: DateTime<Utc>,
|
pub start: DateTime<Utc>,
|
||||||
|
|
||||||
/// Конец пары
|
/// The end of the lesson.
|
||||||
pub end: DateTime<Utc>,
|
pub end: DateTime<Utc>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Type of lesson.
|
||||||
#[derive(Clone, Hash, PartialEq, Debug, Serialize_repr, Deserialize_repr, ToSchema)]
|
#[derive(Clone, Hash, PartialEq, Debug, Serialize_repr, Deserialize_repr, ToSchema)]
|
||||||
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
|
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
|
||||||
#[repr(u8)]
|
#[repr(u8)]
|
||||||
pub enum LessonType {
|
pub enum LessonType {
|
||||||
/// Обычная
|
/// Обычная.
|
||||||
Default = 0,
|
Default = 0,
|
||||||
|
|
||||||
/// Допы
|
/// Допы.
|
||||||
Additional,
|
Additional,
|
||||||
|
|
||||||
/// Перемена
|
/// Перемена.
|
||||||
Break,
|
Break,
|
||||||
|
|
||||||
/// Консультация
|
/// Консультация.
|
||||||
Consultation,
|
Consultation,
|
||||||
|
|
||||||
/// Самостоятельная работа
|
/// Самостоятельная работа.
|
||||||
IndependentWork,
|
IndependentWork,
|
||||||
|
|
||||||
/// Зачёт
|
/// Зачёт.
|
||||||
Exam,
|
Exam,
|
||||||
|
|
||||||
/// Зачет с оценкой
|
/// Зачёт с оценкой.
|
||||||
ExamWithGrade,
|
ExamWithGrade,
|
||||||
|
|
||||||
/// Экзамен
|
/// Экзамен.
|
||||||
ExamDefault,
|
ExamDefault,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Hash, Debug, Serialize, Deserialize, ToSchema)]
|
#[derive(Clone, Hash, Debug, Serialize, Deserialize, ToSchema)]
|
||||||
pub struct LessonSubGroup {
|
pub struct LessonSubGroup {
|
||||||
/// Номер подгруппы
|
/// Index of subgroup.
|
||||||
pub number: u8,
|
pub number: u8,
|
||||||
|
|
||||||
/// Кабинет, если присутствует
|
/// Cabinet, if present.
|
||||||
pub cabinet: Option<String>,
|
pub cabinet: Option<String>,
|
||||||
|
|
||||||
/// Фио преподавателя
|
/// Full name of the teacher.
|
||||||
pub teacher: String,
|
pub teacher: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Hash, Debug, Serialize, Deserialize, ToSchema)]
|
#[derive(Clone, Hash, Debug, Serialize, Deserialize, ToSchema)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct Lesson {
|
pub struct Lesson {
|
||||||
/// Тип занятия
|
/// Type.
|
||||||
#[serde(rename = "type")]
|
#[serde(rename = "type")]
|
||||||
pub lesson_type: LessonType,
|
pub lesson_type: LessonType,
|
||||||
|
|
||||||
/// Индексы пар, если присутствуют
|
/// Lesson indexes, if present.
|
||||||
pub default_range: Option<[u8; 2]>,
|
pub default_range: Option<[u8; 2]>,
|
||||||
|
|
||||||
/// Название занятия
|
/// Name.
|
||||||
pub name: Option<String>,
|
pub name: Option<String>,
|
||||||
|
|
||||||
/// Начало и конец занятия
|
/// The beginning and end.
|
||||||
pub time: LessonTime,
|
pub time: LessonTime,
|
||||||
|
|
||||||
/// Список подгрупп
|
/// List of subgroups.
|
||||||
#[serde(rename = "subGroups")]
|
#[serde(rename = "subGroups")]
|
||||||
pub subgroups: Option<Vec<LessonSubGroup>>,
|
pub subgroups: Option<Vec<LessonSubGroup>>,
|
||||||
|
|
||||||
/// Группа, если это расписание для преподавателей
|
/// Group name, if this is a schedule for teachers.
|
||||||
pub group: Option<String>,
|
pub group: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Hash, Debug, Serialize, Deserialize, ToSchema)]
|
#[derive(Clone, Hash, Debug, Serialize, Deserialize, ToSchema)]
|
||||||
pub struct Day {
|
pub struct Day {
|
||||||
/// День недели
|
/// Day of the week.
|
||||||
pub name: String,
|
pub name: String,
|
||||||
|
|
||||||
/// Адрес другого корпуса
|
/// Address of another corps.
|
||||||
pub street: Option<String>,
|
pub street: Option<String>,
|
||||||
|
|
||||||
/// Дата
|
/// Date.
|
||||||
pub date: DateTime<Utc>,
|
pub date: DateTime<Utc>,
|
||||||
|
|
||||||
/// Список пар в этот день
|
/// List of lessons on this day.
|
||||||
pub lessons: Vec<Lesson>,
|
pub lessons: Vec<Lesson>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Hash, Debug, Serialize, Deserialize, ToSchema)]
|
#[derive(Clone, Hash, Debug, Serialize, Deserialize, ToSchema)]
|
||||||
pub struct ScheduleEntry {
|
pub struct ScheduleEntry {
|
||||||
/// Название группы или ФИО преподавателя
|
/// The name of the group or name of the teacher.
|
||||||
pub name: String,
|
pub name: String,
|
||||||
|
|
||||||
/// Список из шести дней
|
/// List of six days.
|
||||||
pub days: Vec<Day>,
|
pub days: Vec<Day>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct ParseResult {
|
pub struct ParseResult {
|
||||||
/// Список групп
|
/// List of groups.
|
||||||
pub groups: HashMap<String, ScheduleEntry>,
|
pub groups: HashMap<String, ScheduleEntry>,
|
||||||
|
|
||||||
/// Список преподавателей
|
/// List of teachers.
|
||||||
pub teachers: HashMap<String, ScheduleEntry>,
|
pub teachers: HashMap<String, ScheduleEntry>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Display, Clone, ToSchema)]
|
#[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)]
|
||||||
pub enum ParseError {
|
pub enum ParseError {
|
||||||
/// Ошибки связанные с чтением XLS файла.
|
/// Errors related to reading XLS file.
|
||||||
#[display("{}: Failed to read XLS file.", "_0")]
|
#[display("{_0:?}: Failed to read XLS file.")]
|
||||||
#[schema(value_type = String)]
|
#[schema(value_type = String)]
|
||||||
BadXLS(Arc<calamine::XlsError>),
|
BadXLS(Arc<calamine::XlsError>),
|
||||||
|
|
||||||
/// Не найдено ни одного листа
|
/// Not a single sheet was found.
|
||||||
#[display("No work sheets found.")]
|
#[display("No work sheets found.")]
|
||||||
NoWorkSheets,
|
NoWorkSheets,
|
||||||
|
|
||||||
/// Отсутствуют данные об границах листа
|
/// There are no data on the boundaries of the sheet.
|
||||||
#[display("There is no data on work sheet boundaries.")]
|
#[display("There is no data on work sheet boundaries.")]
|
||||||
UnknownWorkSheetRange,
|
UnknownWorkSheetRange,
|
||||||
|
|
||||||
/// Не удалось прочитать начало и конец пары из строки
|
/// Failed to read the beginning and end of the lesson from the line
|
||||||
#[display("Failed to read lesson start and end times from string.")]
|
#[display("Failed to read lesson start and end times from {_0}.")]
|
||||||
GlobalTime,
|
GlobalTime(ErrorCell),
|
||||||
|
|
||||||
/// Не найдены начало и конец соответствующее паре
|
/// Not found the beginning and the end corresponding to the lesson.
|
||||||
#[display("No start and end times matching the lesson was found.")]
|
#[display("No start and end times matching the lesson (at {_0}) was found.")]
|
||||||
LessonTimeNotFound,
|
LessonTimeNotFound(ErrorCellPos),
|
||||||
|
|
||||||
/// Не удалось прочитать индекс подгруппы
|
|
||||||
#[display("Failed to read subgroup index.")]
|
|
||||||
SubgroupIndexParsingFailed,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Serialize for ParseError {
|
impl Serialize for ParseError {
|
||||||
@@ -152,11 +173,8 @@ impl Serialize for ParseError {
|
|||||||
ParseError::UnknownWorkSheetRange => {
|
ParseError::UnknownWorkSheetRange => {
|
||||||
serializer.serialize_str("UNKNOWN_WORK_SHEET_RANGE")
|
serializer.serialize_str("UNKNOWN_WORK_SHEET_RANGE")
|
||||||
}
|
}
|
||||||
ParseError::GlobalTime => serializer.serialize_str("GLOBAL_TIME"),
|
ParseError::GlobalTime(_) => serializer.serialize_str("GLOBAL_TIME"),
|
||||||
ParseError::LessonTimeNotFound => serializer.serialize_str("LESSON_TIME_NOT_FOUND"),
|
ParseError::LessonTimeNotFound(_) => serializer.serialize_str("LESSON_TIME_NOT_FOUND"),
|
||||||
ParseError::SubgroupIndexParsingFailed => {
|
|
||||||
serializer.serialize_str("SUBGROUP_INDEX_PARSING_FAILED")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,6 @@
|
|||||||
use crate::utility::jwt::DEFAULT_ALGORITHM;
|
|
||||||
use jsonwebtoken::errors::ErrorKind;
|
use jsonwebtoken::errors::ErrorKind;
|
||||||
use jsonwebtoken::{decode, DecodingKey, Validation};
|
use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::env;
|
|
||||||
use std::sync::LazyLock;
|
|
||||||
|
|
||||||
#[derive(Deserialize, Serialize)]
|
#[derive(Deserialize, Serialize)]
|
||||||
struct TokenData {
|
struct TokenData {
|
||||||
@@ -17,7 +14,7 @@ struct TokenData {
|
|||||||
|
|
||||||
#[derive(Debug, Serialize, Deserialize)]
|
#[derive(Debug, Serialize, Deserialize)]
|
||||||
struct Claims {
|
struct Claims {
|
||||||
sub: String,
|
sub: i32,
|
||||||
iis: String,
|
iis: String,
|
||||||
jti: i32,
|
jti: i32,
|
||||||
app: i32,
|
app: i32,
|
||||||
@@ -52,17 +49,10 @@ const VK_PUBLIC_KEY: &str = concat!(
|
|||||||
"-----END PUBLIC KEY-----"
|
"-----END PUBLIC KEY-----"
|
||||||
);
|
);
|
||||||
|
|
||||||
static VK_ID_CLIENT_ID: LazyLock<i32> = LazyLock::new(|| {
|
pub fn parse_vk_id(token_str: &String, client_id: i32) -> Result<i32, Error> {
|
||||||
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();
|
let dkey = DecodingKey::from_rsa_pem(VK_PUBLIC_KEY.as_bytes()).unwrap();
|
||||||
|
|
||||||
match decode::<Claims>(&token_str, &dkey, &Validation::new(DEFAULT_ALGORITHM)) {
|
match decode::<Claims>(&token_str, &dkey, &Validation::new(Algorithm::RS256)) {
|
||||||
Ok(token_data) => {
|
Ok(token_data) => {
|
||||||
let claims = token_data.claims;
|
let claims = token_data.claims;
|
||||||
|
|
||||||
@@ -70,13 +60,10 @@ pub fn parse_vk_id(token_str: &String) -> Result<i32, Error> {
|
|||||||
Err(Error::UnknownIssuer(claims.iis))
|
Err(Error::UnknownIssuer(claims.iis))
|
||||||
} else if claims.jti != 21 {
|
} else if claims.jti != 21 {
|
||||||
Err(Error::UnknownType(claims.jti))
|
Err(Error::UnknownType(claims.jti))
|
||||||
} else if claims.app != *VK_ID_CLIENT_ID {
|
} else if claims.app != client_id {
|
||||||
Err(Error::UnknownClientId(claims.app))
|
Err(Error::UnknownClientId(claims.app))
|
||||||
} else {
|
} else {
|
||||||
match claims.sub.parse::<i32>() {
|
Ok(claims.sub)
|
||||||
Ok(sub) => Ok(sub),
|
|
||||||
Err(_) => Err(Error::InvalidToken),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(err) => Err(match err.into_kind() {
|
Err(err) => Err(match err.into_kind() {
|
||||||
|
|||||||
@@ -5,10 +5,10 @@ use crate::routes::auth::shared::parse_vk_id;
|
|||||||
use crate::routes::auth::sign_in::schema::SignInData::{Default, Vk};
|
use crate::routes::auth::sign_in::schema::SignInData::{Default, Vk};
|
||||||
use crate::routes::schema::user::UserResponse;
|
use crate::routes::schema::user::UserResponse;
|
||||||
use crate::routes::schema::{IntoResponseAsError, ResponseError};
|
use crate::routes::schema::{IntoResponseAsError, ResponseError};
|
||||||
use crate::{utility, AppState};
|
use crate::utility::mutex::MutexScope;
|
||||||
|
use crate::{AppState, utility};
|
||||||
use actix_web::{post, web};
|
use actix_web::{post, web};
|
||||||
use diesel::SaveChangesDsl;
|
use diesel::SaveChangesDsl;
|
||||||
use std::ops::DerefMut;
|
|
||||||
use web::Json;
|
use web::Json;
|
||||||
|
|
||||||
async fn sign_in_combined(
|
async fn sign_in_combined(
|
||||||
@@ -16,8 +16,8 @@ async fn sign_in_combined(
|
|||||||
app_state: &web::Data<AppState>,
|
app_state: &web::Data<AppState>,
|
||||||
) -> Result<UserResponse, ErrorCode> {
|
) -> Result<UserResponse, ErrorCode> {
|
||||||
let user = match &data {
|
let user = match &data {
|
||||||
Default(data) => driver::users::get_by_username(&app_state.database, &data.username),
|
Default(data) => driver::users::get_by_username(&app_state, &data.username),
|
||||||
Vk(id) => driver::users::get_by_vk_id(&app_state.database, *id),
|
Vk(id) => driver::users::get_by_vk_id(&app_state, *id),
|
||||||
};
|
};
|
||||||
|
|
||||||
match user {
|
match user {
|
||||||
@@ -35,13 +35,12 @@ async fn sign_in_combined(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut lock = app_state.connection();
|
|
||||||
let conn = lock.deref_mut();
|
|
||||||
|
|
||||||
user.access_token = utility::jwt::encode(&user.id);
|
user.access_token = utility::jwt::encode(&user.id);
|
||||||
|
|
||||||
|
app_state.database.scope(|conn| {
|
||||||
user.save_changes::<User>(conn)
|
user.save_changes::<User>(conn)
|
||||||
.expect("Failed to update user");
|
.expect("Failed to update user")
|
||||||
|
});
|
||||||
|
|
||||||
Ok(user.into())
|
Ok(user.into())
|
||||||
}
|
}
|
||||||
@@ -56,7 +55,9 @@ async fn sign_in_combined(
|
|||||||
))]
|
))]
|
||||||
#[post("/sign-in")]
|
#[post("/sign-in")]
|
||||||
pub async fn sign_in(data: Json<Request>, app_state: web::Data<AppState>) -> ServiceResponse {
|
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()
|
sign_in_combined(Default(data.into_inner()), &app_state)
|
||||||
|
.await
|
||||||
|
.into()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[utoipa::path(responses(
|
#[utoipa::path(responses(
|
||||||
@@ -64,10 +65,13 @@ pub async fn sign_in(data: Json<Request>, app_state: web::Data<AppState>) -> Ser
|
|||||||
(status = NOT_ACCEPTABLE, body = ResponseError<ErrorCode>)
|
(status = NOT_ACCEPTABLE, body = ResponseError<ErrorCode>)
|
||||||
))]
|
))]
|
||||||
#[post("/sign-in-vk")]
|
#[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();
|
let data = data_json.into_inner();
|
||||||
|
|
||||||
match parse_vk_id(&data.access_token) {
|
match parse_vk_id(&data.access_token, app_state.vk_id.client_id) {
|
||||||
Ok(id) => sign_in_combined(Vk(id), &app_state).await.into(),
|
Ok(id) => sign_in_combined(Vk(id), &app_state).await.into(),
|
||||||
Err(_) => ErrorCode::InvalidVkAccessToken.into_response(),
|
Err(_) => ErrorCode::InvalidVkAccessToken.into_response(),
|
||||||
}
|
}
|
||||||
@@ -82,11 +86,11 @@ mod schema {
|
|||||||
#[derive(Deserialize, Serialize, ToSchema)]
|
#[derive(Deserialize, Serialize, ToSchema)]
|
||||||
#[schema(as = SignIn::Request)]
|
#[schema(as = SignIn::Request)]
|
||||||
pub struct Request {
|
pub struct Request {
|
||||||
/// Имя пользователя
|
/// User name.
|
||||||
#[schema(examples("n08i40k"))]
|
#[schema(examples("n08i40k"))]
|
||||||
pub username: String,
|
pub username: String,
|
||||||
|
|
||||||
/// Пароль
|
/// Password.
|
||||||
pub password: String,
|
pub password: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -98,7 +102,7 @@ mod schema {
|
|||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
#[schema(as = SignInVk::Request)]
|
#[schema(as = SignInVk::Request)]
|
||||||
pub struct Request {
|
pub struct Request {
|
||||||
/// Токен VK ID
|
/// VK ID token.
|
||||||
pub access_token: String,
|
pub access_token: String,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -110,21 +114,21 @@ mod schema {
|
|||||||
#[schema(as = SignIn::ErrorCode)]
|
#[schema(as = SignIn::ErrorCode)]
|
||||||
#[status_code = "actix_web::http::StatusCode::NOT_ACCEPTABLE"]
|
#[status_code = "actix_web::http::StatusCode::NOT_ACCEPTABLE"]
|
||||||
pub enum ErrorCode {
|
pub enum ErrorCode {
|
||||||
/// Некорректное имя пользователя или пароль
|
/// Incorrect username or password.
|
||||||
IncorrectCredentials,
|
IncorrectCredentials,
|
||||||
|
|
||||||
/// Недействительный токен VK ID
|
/// Invalid VK ID token.
|
||||||
InvalidVkAccessToken,
|
InvalidVkAccessToken,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Internal
|
/// Internal
|
||||||
|
|
||||||
/// Тип авторизации
|
/// Type of authorization.
|
||||||
pub enum SignInData {
|
pub enum SignInData {
|
||||||
/// Имя пользователя и пароль
|
/// User and password name and password.
|
||||||
Default(Request),
|
Default(Request),
|
||||||
|
|
||||||
/// Идентификатор привязанного аккаунта VK
|
/// Identifier of the attached account VK.
|
||||||
Vk(i32),
|
Vk(i32),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -146,7 +150,7 @@ mod tests {
|
|||||||
use std::fmt::Write;
|
use std::fmt::Write;
|
||||||
|
|
||||||
async fn sign_in_client(data: Request) -> ServiceResponse {
|
async fn sign_in_client(data: Request) -> ServiceResponse {
|
||||||
let app = test_app(test_app_state(), sign_in).await;
|
let app = test_app(test_app_state().await, sign_in).await;
|
||||||
|
|
||||||
let req = test::TestRequest::with_uri("/sign-in")
|
let req = test::TestRequest::with_uri("/sign-in")
|
||||||
.method(Method::POST)
|
.method(Method::POST)
|
||||||
@@ -156,7 +160,7 @@ mod tests {
|
|||||||
test::call_service(&app, req).await
|
test::call_service(&app, req).await
|
||||||
}
|
}
|
||||||
|
|
||||||
fn prepare(username: String) {
|
async fn prepare(username: String) {
|
||||||
let id = {
|
let id = {
|
||||||
let mut sha = Sha1::new();
|
let mut sha = Sha1::new();
|
||||||
sha.update(&username);
|
sha.update(&username);
|
||||||
@@ -174,9 +178,9 @@ mod tests {
|
|||||||
|
|
||||||
test_env();
|
test_env();
|
||||||
|
|
||||||
let app_state = static_app_state();
|
let app_state = static_app_state().await;
|
||||||
driver::users::insert_or_ignore(
|
driver::users::insert_or_ignore(
|
||||||
&app_state.database,
|
&app_state,
|
||||||
&User {
|
&User {
|
||||||
id: id.clone(),
|
id: id.clone(),
|
||||||
username,
|
username,
|
||||||
@@ -193,7 +197,7 @@ mod tests {
|
|||||||
|
|
||||||
#[actix_web::test]
|
#[actix_web::test]
|
||||||
async fn sign_in_ok() {
|
async fn sign_in_ok() {
|
||||||
prepare("test::sign_in_ok".to_string());
|
prepare("test::sign_in_ok".to_string()).await;
|
||||||
|
|
||||||
let resp = sign_in_client(Request {
|
let resp = sign_in_client(Request {
|
||||||
username: "test::sign_in_ok".to_string(),
|
username: "test::sign_in_ok".to_string(),
|
||||||
@@ -206,7 +210,7 @@ mod tests {
|
|||||||
|
|
||||||
#[actix_web::test]
|
#[actix_web::test]
|
||||||
async fn sign_in_err() {
|
async fn sign_in_err() {
|
||||||
prepare("test::sign_in_err".to_string());
|
prepare("test::sign_in_err".to_string()).await;
|
||||||
|
|
||||||
let invalid_username = sign_in_client(Request {
|
let invalid_username = sign_in_client(Request {
|
||||||
username: "test::sign_in_err::username".to_string(),
|
username: "test::sign_in_err::username".to_string(),
|
||||||
|
|||||||
@@ -28,19 +28,19 @@ async fn sign_up_combined(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// If user with specified username already exists.
|
// If user with specified username already exists.
|
||||||
if driver::users::contains_by_username(&app_state.database, &data.username) {
|
if driver::users::contains_by_username(&app_state, &data.username) {
|
||||||
return Err(ErrorCode::UsernameAlreadyExists);
|
return Err(ErrorCode::UsernameAlreadyExists);
|
||||||
}
|
}
|
||||||
|
|
||||||
// If user with specified VKID already exists.
|
// If user with specified VKID already exists.
|
||||||
if let Some(id) = data.vk_id {
|
if let Some(id) = data.vk_id {
|
||||||
if driver::users::contains_by_vk_id(&app_state.database, id) {
|
if driver::users::contains_by_vk_id(&app_state, id) {
|
||||||
return Err(ErrorCode::VkAlreadyExists);
|
return Err(ErrorCode::VkAlreadyExists);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let user = data.into();
|
let user = data.into();
|
||||||
driver::users::insert(&app_state.database, &user).unwrap();
|
driver::users::insert(&app_state, &user).unwrap();
|
||||||
|
|
||||||
Ok(UserResponse::from(&user)).into()
|
Ok(UserResponse::from(&user)).into()
|
||||||
}
|
}
|
||||||
@@ -50,10 +50,7 @@ async fn sign_up_combined(
|
|||||||
(status = NOT_ACCEPTABLE, body = ResponseError<ErrorCode>)
|
(status = NOT_ACCEPTABLE, body = ResponseError<ErrorCode>)
|
||||||
))]
|
))]
|
||||||
#[post("/sign-up")]
|
#[post("/sign-up")]
|
||||||
pub async fn sign_up(
|
pub async fn sign_up(data_json: Json<Request>, app_state: web::Data<AppState>) -> ServiceResponse {
|
||||||
data_json: Json<Request>,
|
|
||||||
app_state: web::Data<AppState>,
|
|
||||||
) -> ServiceResponse {
|
|
||||||
let data = data_json.into_inner();
|
let data = data_json.into_inner();
|
||||||
|
|
||||||
sign_up_combined(
|
sign_up_combined(
|
||||||
@@ -82,7 +79,7 @@ pub async fn sign_up_vk(
|
|||||||
) -> ServiceResponse {
|
) -> ServiceResponse {
|
||||||
let data = data_json.into_inner();
|
let data = data_json.into_inner();
|
||||||
|
|
||||||
match parse_vk_id(&data.access_token) {
|
match parse_vk_id(&data.access_token, app_state.vk_id.client_id) {
|
||||||
Ok(id) => sign_up_combined(
|
Ok(id) => sign_up_combined(
|
||||||
SignUpData {
|
SignUpData {
|
||||||
username: data.username,
|
username: data.username,
|
||||||
@@ -124,21 +121,21 @@ mod schema {
|
|||||||
#[derive(Serialize, Deserialize, utoipa::ToSchema)]
|
#[derive(Serialize, Deserialize, utoipa::ToSchema)]
|
||||||
#[schema(as = SignUp::Request)]
|
#[schema(as = SignUp::Request)]
|
||||||
pub struct Request {
|
pub struct Request {
|
||||||
/// Имя пользователя
|
/// User name.
|
||||||
#[schema(examples("n08i40k"))]
|
#[schema(examples("n08i40k"))]
|
||||||
pub username: String,
|
pub username: String,
|
||||||
|
|
||||||
/// Пароль
|
/// Password.
|
||||||
pub password: String,
|
pub password: String,
|
||||||
|
|
||||||
/// Группа
|
/// Group.
|
||||||
#[schema(examples("ИС-214/23"))]
|
#[schema(examples("ИС-214/23"))]
|
||||||
pub group: String,
|
pub group: String,
|
||||||
|
|
||||||
/// Роль
|
/// Role.
|
||||||
pub role: UserRole,
|
pub role: UserRole,
|
||||||
|
|
||||||
/// Версия установленного приложения Polytechnic+
|
/// Version of the installed Polytechnic+ application.
|
||||||
#[schema(examples("3.0.0"))]
|
#[schema(examples("3.0.0"))]
|
||||||
pub version: String,
|
pub version: String,
|
||||||
}
|
}
|
||||||
@@ -151,21 +148,21 @@ mod schema {
|
|||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
#[schema(as = SignUpVk::Request)]
|
#[schema(as = SignUpVk::Request)]
|
||||||
pub struct Request {
|
pub struct Request {
|
||||||
/// Токен VK ID
|
/// VK ID token.
|
||||||
pub access_token: String,
|
pub access_token: String,
|
||||||
|
|
||||||
/// Имя пользователя
|
/// User name.
|
||||||
#[schema(examples("n08i40k"))]
|
#[schema(examples("n08i40k"))]
|
||||||
pub username: String,
|
pub username: String,
|
||||||
|
|
||||||
/// Группа
|
/// Group.
|
||||||
#[schema(examples("ИС-214/23"))]
|
#[schema(examples("ИС-214/23"))]
|
||||||
pub group: String,
|
pub group: String,
|
||||||
|
|
||||||
/// Роль
|
/// Role.
|
||||||
pub role: UserRole,
|
pub role: UserRole,
|
||||||
|
|
||||||
/// Версия установленного приложения Polytechnic+
|
/// Version of the installed Polytechnic+ application.
|
||||||
#[schema(examples("3.0.0"))]
|
#[schema(examples("3.0.0"))]
|
||||||
pub version: String,
|
pub version: String,
|
||||||
}
|
}
|
||||||
@@ -178,44 +175,44 @@ mod schema {
|
|||||||
#[schema(as = SignUp::ErrorCode)]
|
#[schema(as = SignUp::ErrorCode)]
|
||||||
#[status_code = "actix_web::http::StatusCode::NOT_ACCEPTABLE"]
|
#[status_code = "actix_web::http::StatusCode::NOT_ACCEPTABLE"]
|
||||||
pub enum ErrorCode {
|
pub enum ErrorCode {
|
||||||
/// Передана роль ADMIN
|
/// Conveyed the role of Admin.
|
||||||
DisallowedRole,
|
DisallowedRole,
|
||||||
|
|
||||||
/// Неизвестное название группы
|
/// Unknown name of the group.
|
||||||
InvalidGroupName,
|
InvalidGroupName,
|
||||||
|
|
||||||
/// Пользователь с таким именем уже зарегистрирован
|
/// User with this name is already registered.
|
||||||
UsernameAlreadyExists,
|
UsernameAlreadyExists,
|
||||||
|
|
||||||
/// Недействительный токен VK ID
|
/// Invalid VK ID token.
|
||||||
InvalidVkAccessToken,
|
InvalidVkAccessToken,
|
||||||
|
|
||||||
/// Пользователь с таким аккаунтом VK уже зарегистрирован
|
/// User with such an account VK is already registered.
|
||||||
VkAlreadyExists,
|
VkAlreadyExists,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Internal
|
/// Internal
|
||||||
|
|
||||||
/// Данные для регистрации
|
/// Data for registration.
|
||||||
pub struct SignUpData {
|
pub struct SignUpData {
|
||||||
/// Имя пользователя
|
/// User name.
|
||||||
pub username: String,
|
pub username: String,
|
||||||
|
|
||||||
/// Пароль
|
/// Password.
|
||||||
///
|
///
|
||||||
/// Должен присутствовать даже если регистрация происходит с помощью токена VK ID
|
/// Should be present even if registration occurs using the VK ID token.
|
||||||
pub password: String,
|
pub password: String,
|
||||||
|
|
||||||
/// Идентификатор аккаунта VK
|
/// Account identifier VK.
|
||||||
pub vk_id: Option<i32>,
|
pub vk_id: Option<i32>,
|
||||||
|
|
||||||
/// Группа
|
/// Group.
|
||||||
pub group: String,
|
pub group: String,
|
||||||
|
|
||||||
/// Роль
|
/// Role.
|
||||||
pub role: UserRole,
|
pub role: UserRole,
|
||||||
|
|
||||||
/// Версия установленного приложения Polytechnic+
|
/// Version of the installed Polytechnic+ application.
|
||||||
pub version: String,
|
pub version: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -258,7 +255,7 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn sign_up_client(data: SignUpPartial) -> ServiceResponse {
|
async fn sign_up_client(data: SignUpPartial) -> ServiceResponse {
|
||||||
let app = test_app(test_app_state(), sign_up).await;
|
let app = test_app(test_app_state().await, sign_up).await;
|
||||||
|
|
||||||
let req = test::TestRequest::with_uri("/sign-up")
|
let req = test::TestRequest::with_uri("/sign-up")
|
||||||
.method(Method::POST)
|
.method(Method::POST)
|
||||||
@@ -280,8 +277,8 @@ mod tests {
|
|||||||
|
|
||||||
test_env();
|
test_env();
|
||||||
|
|
||||||
let app_state = static_app_state();
|
let app_state = static_app_state().await;
|
||||||
driver::users::delete_by_username(&app_state.database, &"test::sign_up_valid".to_string());
|
driver::users::delete_by_username(&app_state, &"test::sign_up_valid".to_string());
|
||||||
|
|
||||||
// test
|
// test
|
||||||
|
|
||||||
@@ -301,11 +298,8 @@ mod tests {
|
|||||||
|
|
||||||
test_env();
|
test_env();
|
||||||
|
|
||||||
let app_state = static_app_state();
|
let app_state = static_app_state().await;
|
||||||
driver::users::delete_by_username(
|
driver::users::delete_by_username(&app_state, &"test::sign_up_multiple".to_string());
|
||||||
&app_state.database,
|
|
||||||
&"test::sign_up_multiple".to_string(),
|
|
||||||
);
|
|
||||||
|
|
||||||
let create = sign_up_client(SignUpPartial {
|
let create = sign_up_client(SignUpPartial {
|
||||||
username: "test::sign_up_multiple".to_string(),
|
username: "test::sign_up_multiple".to_string(),
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
mod update_callback;
|
mod update_callback;
|
||||||
|
mod set_token;
|
||||||
|
|
||||||
pub use update_callback::*;
|
pub use update_callback::*;
|
||||||
|
pub use set_token::*;
|
||||||
|
|||||||
114
src/routes/fcm/set_token.rs
Normal file
114
src/routes/fcm/set_token.rs
Normal file
@@ -0,0 +1,114 @@
|
|||||||
|
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()
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
use crate::app_state::AppState;
|
use crate::app_state::AppState;
|
||||||
use crate::database::models::User;
|
use crate::database::models::User;
|
||||||
use crate::extractors::base::SyncExtractor;
|
use crate::extractors::base::SyncExtractor;
|
||||||
|
use crate::utility::mutex::MutexScope;
|
||||||
use actix_web::{HttpResponse, Responder, post, web};
|
use actix_web::{HttpResponse, Responder, post, web};
|
||||||
use diesel::SaveChangesDsl;
|
use diesel::SaveChangesDsl;
|
||||||
|
|
||||||
@@ -18,7 +19,10 @@ async fn update_callback(
|
|||||||
|
|
||||||
user.version = version.into_inner();
|
user.version = version.into_inner();
|
||||||
|
|
||||||
match app_state.lock_connection(|con| user.save_changes::<User>(con)) {
|
match app_state
|
||||||
|
.database
|
||||||
|
.scope(|conn| user.save_changes::<User>(conn))
|
||||||
|
{
|
||||||
Ok(_) => HttpResponse::Ok(),
|
Ok(_) => HttpResponse::Ok(),
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
eprintln!("Failed to update user: {}", e);
|
eprintln!("Failed to update user: {}", e);
|
||||||
|
|||||||
@@ -25,10 +25,7 @@ use actix_web::{get, web};
|
|||||||
),
|
),
|
||||||
))]
|
))]
|
||||||
#[get("/group")]
|
#[get("/group")]
|
||||||
pub async fn group(
|
pub async fn group(user: SyncExtractor<User>, app_state: web::Data<AppState>) -> ServiceResponse {
|
||||||
user: SyncExtractor<User>,
|
|
||||||
app_state: web::Data<AppState>,
|
|
||||||
) -> ServiceResponse {
|
|
||||||
// Prevent thread lock
|
// Prevent thread lock
|
||||||
let schedule_lock = app_state.schedule.lock().unwrap();
|
let schedule_lock = app_state.schedule.lock().unwrap();
|
||||||
|
|
||||||
@@ -55,18 +52,18 @@ mod schema {
|
|||||||
#[schema(as = GetGroup::Response)]
|
#[schema(as = GetGroup::Response)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct Response {
|
pub struct Response {
|
||||||
/// Расписание группы
|
/// Group schedule.
|
||||||
pub group: ScheduleEntry,
|
pub group: ScheduleEntry,
|
||||||
|
|
||||||
/// Устаревшая переменная
|
/// ## Outdated variable.
|
||||||
///
|
///
|
||||||
/// По умолчанию возвращается пустой список
|
/// By default, an empty list is returned.
|
||||||
#[deprecated = "Will be removed in future versions"]
|
#[deprecated = "Will be removed in future versions"]
|
||||||
pub updated: Vec<i32>,
|
pub updated: Vec<i32>,
|
||||||
|
|
||||||
/// Устаревшая переменная
|
/// ## Outdated variable.
|
||||||
///
|
///
|
||||||
/// По умолчанию начальная дата по Unix
|
/// By default, the initial date for unix.
|
||||||
#[deprecated = "Will be removed in future versions"]
|
#[deprecated = "Will be removed in future versions"]
|
||||||
pub updated_at: DateTime<Utc>,
|
pub updated_at: DateTime<Utc>,
|
||||||
}
|
}
|
||||||
@@ -86,12 +83,12 @@ mod schema {
|
|||||||
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
|
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
|
||||||
#[schema(as = GroupSchedule::ErrorCode)]
|
#[schema(as = GroupSchedule::ErrorCode)]
|
||||||
pub enum ErrorCode {
|
pub enum ErrorCode {
|
||||||
/// Расписания ещё не получены
|
/// Schedules have not yet been parsed.
|
||||||
#[status_code = "actix_web::http::StatusCode::SERVICE_UNAVAILABLE"]
|
#[status_code = "actix_web::http::StatusCode::SERVICE_UNAVAILABLE"]
|
||||||
#[display("Schedule not parsed yet.")]
|
#[display("Schedule not parsed yet.")]
|
||||||
NoSchedule,
|
NoSchedule,
|
||||||
|
|
||||||
/// Группа не найдена
|
/// Group not found.
|
||||||
#[status_code = "actix_web::http::StatusCode::NOT_FOUND"]
|
#[status_code = "actix_web::http::StatusCode::NOT_FOUND"]
|
||||||
#[display("Required group not found.")]
|
#[display("Required group not found.")]
|
||||||
NotFound,
|
NotFound,
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ mod schema {
|
|||||||
#[derive(Serialize, ToSchema)]
|
#[derive(Serialize, ToSchema)]
|
||||||
#[schema(as = GetGroupNames::Response)]
|
#[schema(as = GetGroupNames::Response)]
|
||||||
pub struct Response {
|
pub struct Response {
|
||||||
/// Список названий групп отсортированный в алфавитном порядке
|
/// List of group names sorted in alphabetical order.
|
||||||
#[schema(examples(json!(["ИС-214/23"])))]
|
#[schema(examples(json!(["ИС-214/23"])))]
|
||||||
pub names: Vec<String>,
|
pub names: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,23 +8,23 @@ use serde::{Deserialize, Serialize};
|
|||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use utoipa::ToSchema;
|
use utoipa::ToSchema;
|
||||||
|
|
||||||
/// Ответ от сервера с расписаниями
|
/// Response from schedule server.
|
||||||
#[derive(Serialize, ToSchema)]
|
#[derive(Serialize, ToSchema)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct ScheduleView {
|
pub struct ScheduleView {
|
||||||
/// ETag расписания на сервере политехникума
|
/// ETag schedules on polytechnic server.
|
||||||
etag: String,
|
etag: String,
|
||||||
|
|
||||||
/// Дата обновления расписания на сайте политехникума
|
/// Schedule update date on polytechnic website.
|
||||||
uploaded_at: DateTime<Utc>,
|
uploaded_at: DateTime<Utc>,
|
||||||
|
|
||||||
/// Дата последнего скачивания расписания с сервера политехникума
|
/// Date last downloaded from the Polytechnic server.
|
||||||
downloaded_at: DateTime<Utc>,
|
downloaded_at: DateTime<Utc>,
|
||||||
|
|
||||||
/// Расписание групп
|
/// Groups schedule.
|
||||||
groups: HashMap<String, ScheduleEntry>,
|
groups: HashMap<String, ScheduleEntry>,
|
||||||
|
|
||||||
/// Расписание преподавателей
|
/// Teachers schedule.
|
||||||
teachers: HashMap<String, ScheduleEntry>,
|
teachers: HashMap<String, ScheduleEntry>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -33,7 +33,7 @@ pub struct ScheduleView {
|
|||||||
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
|
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
|
||||||
#[schema(as = ScheduleShared::ErrorCode)]
|
#[schema(as = ScheduleShared::ErrorCode)]
|
||||||
pub enum ErrorCode {
|
pub enum ErrorCode {
|
||||||
/// Расписания ещё не получены
|
/// Schedules not yet parsed.
|
||||||
#[display("Schedule not parsed yet.")]
|
#[display("Schedule not parsed yet.")]
|
||||||
NoSchedule,
|
NoSchedule,
|
||||||
}
|
}
|
||||||
@@ -56,22 +56,22 @@ impl TryFrom<&web::Data<AppState>> for ScheduleView {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Статус кешированного расписаний
|
/// Cached schedule status.
|
||||||
#[derive(Serialize, Deserialize, ToSchema, ResponderJson)]
|
#[derive(Serialize, Deserialize, ToSchema, ResponderJson)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct CacheStatus {
|
pub struct CacheStatus {
|
||||||
/// Хеш расписаний
|
/// Schedule hash.
|
||||||
pub cache_hash: String,
|
pub cache_hash: String,
|
||||||
|
|
||||||
/// Требуется ли обновить ссылку на расписание
|
/// Whether the schedule reference needs to be updated.
|
||||||
pub cache_update_required: bool,
|
pub cache_update_required: bool,
|
||||||
|
|
||||||
/// Дата последнего обновления кеша
|
/// Last cache update date.
|
||||||
pub last_cache_update: i64,
|
pub last_cache_update: i64,
|
||||||
|
|
||||||
/// Дата обновления кешированного расписания
|
/// Cached schedule update date.
|
||||||
///
|
///
|
||||||
/// Определяется сервером политехникума
|
/// Determined by the polytechnic's server.
|
||||||
pub last_schedule_update: i64,
|
pub last_schedule_update: i64,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -53,18 +53,18 @@ mod schema {
|
|||||||
#[schema(as = GetTeacher::Response)]
|
#[schema(as = GetTeacher::Response)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct Response {
|
pub struct Response {
|
||||||
/// Расписание преподавателя
|
/// Teacher's schedule.
|
||||||
pub teacher: ScheduleEntry,
|
pub teacher: ScheduleEntry,
|
||||||
|
|
||||||
/// Устаревшая переменная
|
/// ## Deprecated variable.
|
||||||
///
|
///
|
||||||
/// По умолчанию возвращается пустой список
|
/// By default, an empty list is returned.
|
||||||
#[deprecated = "Will be removed in future versions"]
|
#[deprecated = "Will be removed in future versions"]
|
||||||
pub updated: Vec<i32>,
|
pub updated: Vec<i32>,
|
||||||
|
|
||||||
/// Устаревшая переменная
|
/// ## Deprecated variable.
|
||||||
///
|
///
|
||||||
/// По умолчанию начальная дата по Unix
|
/// Defaults to the Unix start date.
|
||||||
#[deprecated = "Will be removed in future versions"]
|
#[deprecated = "Will be removed in future versions"]
|
||||||
pub updated_at: DateTime<Utc>,
|
pub updated_at: DateTime<Utc>,
|
||||||
}
|
}
|
||||||
@@ -84,12 +84,12 @@ mod schema {
|
|||||||
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
|
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
|
||||||
#[schema(as = TeacherSchedule::ErrorCode)]
|
#[schema(as = TeacherSchedule::ErrorCode)]
|
||||||
pub enum ErrorCode {
|
pub enum ErrorCode {
|
||||||
/// Расписания ещё не получены
|
/// Schedules have not yet been parsed.
|
||||||
#[status_code = "actix_web::http::StatusCode::SERVICE_UNAVAILABLE"]
|
#[status_code = "actix_web::http::StatusCode::SERVICE_UNAVAILABLE"]
|
||||||
#[display("Schedule not parsed yet.")]
|
#[display("Schedule not parsed yet.")]
|
||||||
NoSchedule,
|
NoSchedule,
|
||||||
|
|
||||||
/// Преподаватель не найден
|
/// Teacher not found.
|
||||||
#[status_code = "actix_web::http::StatusCode::NOT_FOUND"]
|
#[status_code = "actix_web::http::StatusCode::NOT_FOUND"]
|
||||||
#[display("Required teacher not found.")]
|
#[display("Required teacher not found.")]
|
||||||
NotFound,
|
NotFound,
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ mod schema {
|
|||||||
#[derive(Serialize, ToSchema)]
|
#[derive(Serialize, ToSchema)]
|
||||||
#[schema(as = GetTeacherNames::Response)]
|
#[schema(as = GetTeacherNames::Response)]
|
||||||
pub struct Response {
|
pub struct Response {
|
||||||
/// Список имён преподавателей отсортированный в алфавитном порядке
|
/// List of teacher names sorted alphabetically.
|
||||||
#[schema(examples(json!(["Хомченко Н.Е."])))]
|
#[schema(examples(json!(["Хомченко Н.Е."])))]
|
||||||
pub names: Vec<String>,
|
pub names: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ use crate::app_state::Schedule;
|
|||||||
use crate::parser::parse_xls;
|
use crate::parser::parse_xls;
|
||||||
use crate::routes::schedule::schema::CacheStatus;
|
use crate::routes::schedule::schema::CacheStatus;
|
||||||
use crate::routes::schema::{IntoResponseAsError, ResponseError};
|
use crate::routes::schema::{IntoResponseAsError, ResponseError};
|
||||||
use crate::xls_downloader::interface::XLSDownloader;
|
use crate::xls_downloader::interface::{FetchError, XLSDownloader};
|
||||||
use actix_web::web::Json;
|
use actix_web::web::Json;
|
||||||
use actix_web::{patch, web};
|
use actix_web::{patch, web};
|
||||||
use chrono::Utc;
|
use chrono::Utc;
|
||||||
@@ -41,7 +41,7 @@ pub async fn update_download_url(
|
|||||||
}
|
}
|
||||||
|
|
||||||
match downloader.fetch(false).await {
|
match downloader.fetch(false).await {
|
||||||
Ok(download_result) => match parse_xls(download_result.data.as_ref().unwrap()) {
|
Ok(download_result) => match parse_xls(&download_result.data.unwrap()) {
|
||||||
Ok(data) => {
|
Ok(data) => {
|
||||||
*schedule = Some(Schedule {
|
*schedule = Some(Schedule {
|
||||||
etag: download_result.etag,
|
etag: download_result.etag,
|
||||||
@@ -53,21 +53,27 @@ pub async fn update_download_url(
|
|||||||
|
|
||||||
Ok(CacheStatus::from(schedule.as_ref().unwrap())).into()
|
Ok(CacheStatus::from(schedule.as_ref().unwrap())).into()
|
||||||
}
|
}
|
||||||
Err(error) => ErrorCode::InvalidSchedule(error).into_response(),
|
Err(error) => {
|
||||||
|
sentry::capture_error(&error);
|
||||||
|
|
||||||
|
ErrorCode::InvalidSchedule(error).into_response()
|
||||||
|
}
|
||||||
},
|
},
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
eprintln!("Unknown url provided {}", data.url);
|
if let FetchError::Unknown(error) = &error {
|
||||||
eprintln!("{:?}", error);
|
sentry::capture_error(&error);
|
||||||
|
}
|
||||||
|
|
||||||
ErrorCode::DownloadFailed.into_response()
|
ErrorCode::DownloadFailed(error).into_response()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
eprintln!("Unknown url provided {}", data.url);
|
if let FetchError::Unknown(error) = &error {
|
||||||
eprintln!("{:?}", error);
|
sentry::capture_error(&error);
|
||||||
|
}
|
||||||
|
|
||||||
ErrorCode::FetchFailed.into_response()
|
ErrorCode::FetchFailed(error).into_response()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -79,12 +85,13 @@ mod schema {
|
|||||||
use derive_more::Display;
|
use derive_more::Display;
|
||||||
use serde::{Deserialize, Serialize, Serializer};
|
use serde::{Deserialize, Serialize, Serializer};
|
||||||
use utoipa::ToSchema;
|
use utoipa::ToSchema;
|
||||||
|
use crate::xls_downloader::interface::FetchError;
|
||||||
|
|
||||||
pub type ServiceResponse = crate::routes::schema::Response<CacheStatus, ErrorCode>;
|
pub type ServiceResponse = crate::routes::schema::Response<CacheStatus, ErrorCode>;
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, ToSchema)]
|
#[derive(Serialize, Deserialize, ToSchema)]
|
||||||
pub struct Request {
|
pub struct Request {
|
||||||
/// Ссылка на расписание
|
/// Schedule link.
|
||||||
pub url: String,
|
pub url: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -92,26 +99,27 @@ mod schema {
|
|||||||
#[status_code = "actix_web::http::StatusCode::NOT_ACCEPTABLE"]
|
#[status_code = "actix_web::http::StatusCode::NOT_ACCEPTABLE"]
|
||||||
#[schema(as = SetDownloadUrl::ErrorCode)]
|
#[schema(as = SetDownloadUrl::ErrorCode)]
|
||||||
pub enum ErrorCode {
|
pub enum ErrorCode {
|
||||||
/// Передана ссылка с хостом отличающимся от politehnikum-eng.ru
|
/// Transferred link with host different from politehnikum-eng.ru.
|
||||||
#[display("URL with unknown host provided. Provide url with politehnikum-eng.ru host.")]
|
#[display("URL with unknown host provided. Provide url with 'politehnikum-eng.ru' host.")]
|
||||||
NonWhitelistedHost,
|
NonWhitelistedHost,
|
||||||
|
|
||||||
/// Не удалось получить мета-данные файла
|
/// Failed to retrieve file metadata.
|
||||||
#[display("Unable to retrieve metadata from the specified URL.")]
|
#[display("Unable to retrieve metadata from the specified URL: {_0}")]
|
||||||
FetchFailed,
|
FetchFailed(FetchError),
|
||||||
|
|
||||||
/// Не удалось скачать файл
|
/// Failed to download the file.
|
||||||
#[display("Unable to retrieve data from the specified URL.")]
|
#[display("Unable to retrieve data from the specified URL: {_0}")]
|
||||||
DownloadFailed,
|
DownloadFailed(FetchError),
|
||||||
|
|
||||||
/// Ссылка ведёт на устаревшее расписание
|
/// 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.")]
|
#[display("The schedule is older than it already is.")]
|
||||||
OutdatedSchedule,
|
OutdatedSchedule,
|
||||||
|
|
||||||
/// Не удалось преобразовать расписание
|
/// Failed to parse the schedule.
|
||||||
#[display("{}", "_0.display()")]
|
#[display("{_0}")]
|
||||||
InvalidSchedule(ParseError),
|
InvalidSchedule(ParseError),
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -122,8 +130,8 @@ mod schema {
|
|||||||
{
|
{
|
||||||
match self {
|
match self {
|
||||||
ErrorCode::NonWhitelistedHost => serializer.serialize_str("NON_WHITELISTED_HOST"),
|
ErrorCode::NonWhitelistedHost => serializer.serialize_str("NON_WHITELISTED_HOST"),
|
||||||
ErrorCode::FetchFailed => serializer.serialize_str("FETCH_FAILED"),
|
ErrorCode::FetchFailed(_) => serializer.serialize_str("FETCH_FAILED"),
|
||||||
ErrorCode::DownloadFailed => serializer.serialize_str("DOWNLOAD_FAILED"),
|
ErrorCode::DownloadFailed(_) => serializer.serialize_str("DOWNLOAD_FAILED"),
|
||||||
ErrorCode::OutdatedSchedule => serializer.serialize_str("OUTDATED_SCHEDULE"),
|
ErrorCode::OutdatedSchedule => serializer.serialize_str("OUTDATED_SCHEDULE"),
|
||||||
ErrorCode::InvalidSchedule(_) => serializer.serialize_str("INVALID_SCHEDULE"),
|
ErrorCode::InvalidSchedule(_) => serializer.serialize_str("INVALID_SCHEDULE"),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -113,6 +113,7 @@ pub mod user {
|
|||||||
use actix_macros::ResponderJson;
|
use actix_macros::ResponderJson;
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
|
|
||||||
|
//noinspection SpellCheckingInspection
|
||||||
/// Используется для скрытия чувствительных полей, таких как хеш пароля или FCM
|
/// Используется для скрытия чувствительных полей, таких как хеш пароля или FCM
|
||||||
#[derive(Serialize, utoipa::ToSchema, ResponderJson)]
|
#[derive(Serialize, utoipa::ToSchema, ResponderJson)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
@@ -132,7 +133,7 @@ pub mod user {
|
|||||||
/// Роль
|
/// Роль
|
||||||
role: UserRole,
|
role: UserRole,
|
||||||
|
|
||||||
/// Идентификатор прявязанного аккаунта VK
|
/// Идентификатор привязанного аккаунта VK
|
||||||
#[schema(examples(498094647, json!(null)))]
|
#[schema(examples(498094647, json!(null)))]
|
||||||
vk_id: Option<i32>,
|
vk_id: Option<i32>,
|
||||||
|
|
||||||
|
|||||||
85
src/routes/users/change_group.rs
Normal file
85
src/routes/users/change_group.rs
Normal file
@@ -0,0 +1,85 @@
|
|||||||
|
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,
|
||||||
|
}
|
||||||
|
}
|
||||||
70
src/routes/users/change_username.rs
Normal file
70
src/routes/users/change_username.rs
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
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,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
|
mod change_group;
|
||||||
|
mod change_username;
|
||||||
mod me;
|
mod me;
|
||||||
|
|
||||||
|
pub use change_group::*;
|
||||||
|
pub use change_username::*;
|
||||||
pub use me::*;
|
pub use me::*;
|
||||||
|
|
||||||
// TODO: change-username
|
|
||||||
// TODO: change-group
|
|
||||||
@@ -59,15 +59,18 @@ async fn oauth(data: web::Json<Request>, app_state: web::Data<AppState>) -> Serv
|
|||||||
return ErrorCode::VkIdError.into_response();
|
return ErrorCode::VkIdError.into_response();
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Ok(auth_data) = res.json::<VkIdAuthResponse>().await {
|
match res.json::<VkIdAuthResponse>().await {
|
||||||
|
Ok(auth_data) =>
|
||||||
Ok(Response {
|
Ok(Response {
|
||||||
access_token: auth_data.id_token,
|
access_token: auth_data.id_token,
|
||||||
})
|
}).into(),
|
||||||
.into()
|
Err(error) => {
|
||||||
} else {
|
sentry::capture_error(&error);
|
||||||
|
|
||||||
ErrorCode::VkIdError.into_response()
|
ErrorCode::VkIdError.into_response()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
Err(_) => ErrorCode::VkIdError.into_response(),
|
Err(_) => ErrorCode::VkIdError.into_response(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -84,13 +87,13 @@ mod schema {
|
|||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
#[schema(as = VkIdOAuth::Request)]
|
#[schema(as = VkIdOAuth::Request)]
|
||||||
pub struct Request {
|
pub struct Request {
|
||||||
/// Код подтверждения authorization_code
|
/// Код подтверждения authorization_code.
|
||||||
pub code: String,
|
pub code: String,
|
||||||
|
|
||||||
/// Параметр для защиты передаваемых данных
|
/// Parameter to protect transmitted data.
|
||||||
pub code_verifier: String,
|
pub code_verifier: String,
|
||||||
|
|
||||||
/// Идентификатор устройства
|
/// Device ID.
|
||||||
pub device_id: String,
|
pub device_id: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -98,7 +101,7 @@ mod schema {
|
|||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
#[schema(as = VkIdOAuth::Response)]
|
#[schema(as = VkIdOAuth::Response)]
|
||||||
pub struct Response {
|
pub struct Response {
|
||||||
/// ID токен
|
/// ID token.
|
||||||
pub access_token: String,
|
pub access_token: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -107,7 +110,7 @@ mod schema {
|
|||||||
#[schema(as = VkIdOAuth::ErrorCode)]
|
#[schema(as = VkIdOAuth::ErrorCode)]
|
||||||
#[status_code = "actix_web::http::StatusCode::NOT_ACCEPTABLE"]
|
#[status_code = "actix_web::http::StatusCode::NOT_ACCEPTABLE"]
|
||||||
pub enum ErrorCode {
|
pub enum ErrorCode {
|
||||||
/// Сервер VK вернул ошибку
|
/// VK server returned an error.
|
||||||
#[display("VK server returned an error")]
|
#[display("VK server returned an error")]
|
||||||
VkIdError,
|
VkIdError,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,16 +1,16 @@
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
pub(crate) mod tests {
|
pub(crate) mod tests {
|
||||||
use crate::app_state::{app_state, AppState, Schedule};
|
use crate::app_state::{AppState, Schedule, app_state};
|
||||||
use crate::parser::tests::test_result;
|
use crate::parser::tests::test_result;
|
||||||
use actix_web::{web};
|
use actix_web::web;
|
||||||
use std::sync::LazyLock;
|
use tokio::sync::OnceCell;
|
||||||
|
|
||||||
pub fn test_env() {
|
pub fn test_env() {
|
||||||
dotenvy::from_path(".env.test").expect("Failed to load test environment file");
|
dotenvy::from_path(".env.test").expect("Failed to load test environment file");
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn test_app_state() -> web::Data<AppState> {
|
pub async fn test_app_state() -> web::Data<AppState> {
|
||||||
let state = app_state();
|
let state = app_state().await;
|
||||||
let mut schedule_lock = state.schedule.lock().unwrap();
|
let mut schedule_lock = state.schedule.lock().unwrap();
|
||||||
|
|
||||||
*schedule_lock = Some(Schedule {
|
*schedule_lock = Some(Schedule {
|
||||||
@@ -24,9 +24,9 @@ pub(crate) mod tests {
|
|||||||
state.clone()
|
state.clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn static_app_state() -> web::Data<AppState> {
|
pub async fn static_app_state() -> web::Data<AppState> {
|
||||||
static STATE: LazyLock<web::Data<AppState>> = LazyLock::new(|| test_app_state());
|
static STATE: OnceCell<web::Data<AppState>> = OnceCell::const_new();
|
||||||
|
|
||||||
STATE.clone()
|
STATE.get_or_init(|| test_app_state()).await.clone()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ use std::fmt::{Write};
|
|||||||
use std::fmt::Display;
|
use std::fmt::Display;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
/// Ответ от сервера при ошибках внутри Middleware
|
/// Server response to errors within Middleware.
|
||||||
#[derive(Serialize, Deserialize)]
|
#[derive(Serialize, Deserialize)]
|
||||||
pub struct ResponseErrorMessage<T: Display> {
|
pub struct ResponseErrorMessage<T: Display> {
|
||||||
code: T,
|
code: T,
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
use sha1::Digest;
|
use sha1::Digest;
|
||||||
use std::hash::Hasher;
|
use std::hash::Hasher;
|
||||||
|
|
||||||
/// Хешер возвращающий хеш из алгоритма реализующего Digest
|
/// Hesher returning hash from the algorithm implementing Digest
|
||||||
pub struct DigestHasher<D: Digest> {
|
pub struct DigestHasher<D: Digest> {
|
||||||
digest: D,
|
digest: D,
|
||||||
}
|
}
|
||||||
@@ -10,7 +10,7 @@ impl<D> DigestHasher<D>
|
|||||||
where
|
where
|
||||||
D: Digest,
|
D: Digest,
|
||||||
{
|
{
|
||||||
/// Получение хеша
|
/// Obtain hash.
|
||||||
pub fn finalize(self) -> String {
|
pub fn finalize(self) -> String {
|
||||||
hex::encode(self.digest.finalize().0)
|
hex::encode(self.digest.finalize().0)
|
||||||
}
|
}
|
||||||
@@ -20,14 +20,14 @@ impl<D> From<D> for DigestHasher<D>
|
|||||||
where
|
where
|
||||||
D: Digest,
|
D: Digest,
|
||||||
{
|
{
|
||||||
/// Создания хешера из алгоритма реализующего Digest
|
/// Creating a hash from an algorithm implementing Digest.
|
||||||
fn from(digest: D) -> Self {
|
fn from(digest: D) -> Self {
|
||||||
DigestHasher { digest }
|
DigestHasher { digest }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<D: Digest> Hasher for DigestHasher<D> {
|
impl<D: Digest> Hasher for DigestHasher<D> {
|
||||||
/// Заглушка для предотвращения вызова стандартного результата Hasher
|
/// Stopper to prevent calling the standard Hasher result.
|
||||||
fn finish(&self) -> u64 {
|
fn finish(&self) -> u64 {
|
||||||
unimplemented!("Do not call finish()");
|
unimplemented!("Do not call finish()");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,31 +9,31 @@ use std::env;
|
|||||||
use std::mem::discriminant;
|
use std::mem::discriminant;
|
||||||
use std::sync::LazyLock;
|
use std::sync::LazyLock;
|
||||||
|
|
||||||
/// Ключ для верификации токена
|
/// Key for token verification.
|
||||||
static DECODING_KEY: LazyLock<DecodingKey> = LazyLock::new(|| {
|
static DECODING_KEY: LazyLock<DecodingKey> = LazyLock::new(|| {
|
||||||
let secret = env::var("JWT_SECRET").expect("JWT_SECRET must be set");
|
let secret = env::var("JWT_SECRET").expect("JWT_SECRET must be set");
|
||||||
|
|
||||||
DecodingKey::from_secret(secret.as_bytes())
|
DecodingKey::from_secret(secret.as_bytes())
|
||||||
});
|
});
|
||||||
|
|
||||||
/// Ключ для создания подписанного токена
|
/// Key for creating a signed token.
|
||||||
static ENCODING_KEY: LazyLock<EncodingKey> = LazyLock::new(|| {
|
static ENCODING_KEY: LazyLock<EncodingKey> = LazyLock::new(|| {
|
||||||
let secret = env::var("JWT_SECRET").expect("JWT_SECRET must be set");
|
let secret = env::var("JWT_SECRET").expect("JWT_SECRET must be set");
|
||||||
|
|
||||||
EncodingKey::from_secret(secret.as_bytes())
|
EncodingKey::from_secret(secret.as_bytes())
|
||||||
});
|
});
|
||||||
|
|
||||||
/// Ошибки верификации токена
|
/// Token verification errors.
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum Error {
|
pub enum Error {
|
||||||
/// Токен имеет другую подпись
|
/// The token has a different signature.
|
||||||
InvalidSignature,
|
InvalidSignature,
|
||||||
|
|
||||||
/// Ошибка чтения токена
|
/// Token reading error.
|
||||||
InvalidToken(ErrorKind),
|
InvalidToken(ErrorKind),
|
||||||
|
|
||||||
/// Токен просрочен
|
/// Token expired.
|
||||||
Expired,
|
Expired,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -43,26 +43,26 @@ impl PartialEq for Error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Данные, которые хранит в себе токен
|
/// The data the token holds.
|
||||||
#[serde_as]
|
#[serde_as]
|
||||||
#[derive(Debug, Serialize, Deserialize)]
|
#[derive(Debug, Serialize, Deserialize)]
|
||||||
struct Claims {
|
struct Claims {
|
||||||
/// UUID аккаунта пользователя
|
/// User account UUID.
|
||||||
id: String,
|
id: String,
|
||||||
|
|
||||||
/// Дата создания токена
|
/// Token creation date.
|
||||||
#[serde_as(as = "DisplayFromStr")]
|
#[serde_as(as = "DisplayFromStr")]
|
||||||
iat: u64,
|
iat: u64,
|
||||||
|
|
||||||
/// Дата окончания действия токена
|
/// Token expiry date.
|
||||||
#[serde_as(as = "DisplayFromStr")]
|
#[serde_as(as = "DisplayFromStr")]
|
||||||
exp: u64,
|
exp: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Алгоритм подписи токенов
|
/// Token signing algorithm.
|
||||||
pub(crate) const DEFAULT_ALGORITHM: Algorithm = Algorithm::HS256;
|
pub(crate) const DEFAULT_ALGORITHM: Algorithm = Algorithm::HS256;
|
||||||
|
|
||||||
/// Проверка токена и извлечение из него UUID аккаунта пользователя
|
/// Checking the token and extracting the UUID of the user account from it.
|
||||||
pub fn verify_and_decode(token: &String) -> Result<String, Error> {
|
pub fn verify_and_decode(token: &String) -> Result<String, Error> {
|
||||||
let mut validation = Validation::new(DEFAULT_ALGORITHM);
|
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 {
|
pub fn encode(id: &String) -> String {
|
||||||
let header = Header {
|
let header = Header {
|
||||||
typ: Some(String::from("JWT")),
|
typ: Some(String::from("JWT")),
|
||||||
@@ -132,6 +132,7 @@ mod tests {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//noinspection SpellCheckingInspection
|
||||||
#[test]
|
#[test]
|
||||||
fn test_decode_invalid_signature() {
|
fn test_decode_invalid_signature() {
|
||||||
test_env();
|
test_env();
|
||||||
@@ -143,6 +144,7 @@ mod tests {
|
|||||||
assert_eq!(result.err().unwrap(), Error::InvalidSignature);
|
assert_eq!(result.err().unwrap(), Error::InvalidSignature);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//noinspection SpellCheckingInspection
|
||||||
#[test]
|
#[test]
|
||||||
fn test_decode_expired() {
|
fn test_decode_expired() {
|
||||||
test_env();
|
test_env();
|
||||||
@@ -154,6 +156,7 @@ mod tests {
|
|||||||
assert_eq!(result.err().unwrap(), Error::Expired);
|
assert_eq!(result.err().unwrap(), Error::Expired);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//noinspection SpellCheckingInspection
|
||||||
#[test]
|
#[test]
|
||||||
fn test_decode_ok() {
|
fn test_decode_ok() {
|
||||||
test_env();
|
test_env();
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
pub mod jwt;
|
pub mod jwt;
|
||||||
pub mod error;
|
pub mod error;
|
||||||
pub mod hasher;
|
pub mod hasher;
|
||||||
|
pub mod mutex;
|
||||||
77
src/utility/mutex.rs
Normal file
77
src/utility/mutex.rs
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,11 +1,14 @@
|
|||||||
use crate::xls_downloader::interface::{FetchError, FetchOk, FetchResult, XLSDownloader};
|
use crate::xls_downloader::interface::{FetchError, FetchOk, FetchResult, XLSDownloader};
|
||||||
use chrono::{DateTime, Utc};
|
use chrono::{DateTime, Utc};
|
||||||
|
use std::env;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
pub struct BasicXlsDownloader {
|
pub struct BasicXlsDownloader {
|
||||||
pub url: Option<String>,
|
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 client = reqwest::Client::new();
|
||||||
|
|
||||||
let response = if head {
|
let response = if head {
|
||||||
@@ -13,14 +16,14 @@ async fn fetch_specified(url: &String, user_agent: String, head: bool) -> FetchR
|
|||||||
} else {
|
} else {
|
||||||
client.get(url)
|
client.get(url)
|
||||||
}
|
}
|
||||||
.header("User-Agent", user_agent)
|
.header("User-Agent", user_agent.clone())
|
||||||
.send()
|
.send()
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
match response {
|
match response {
|
||||||
Ok(r) => {
|
Ok(r) => {
|
||||||
if r.status().as_u16() != 200 {
|
if r.status().as_u16() != 200 {
|
||||||
return Err(FetchError::BadStatusCode);
|
return Err(FetchError::BadStatusCode(r.status().as_u16()));
|
||||||
}
|
}
|
||||||
|
|
||||||
let headers = r.headers();
|
let headers = r.headers();
|
||||||
@@ -30,11 +33,18 @@ async fn fetch_specified(url: &String, user_agent: String, head: bool) -> FetchR
|
|||||||
let last_modified = headers.get("last-modified");
|
let last_modified = headers.get("last-modified");
|
||||||
let date = headers.get("date");
|
let date = headers.get("date");
|
||||||
|
|
||||||
if content_type.is_none() || etag.is_none() || last_modified.is_none() || date.is_none()
|
if content_type.is_none() {
|
||||||
{
|
Err(FetchError::BadHeaders("Content-Type".to_string()))
|
||||||
Err(FetchError::BadHeaders)
|
} else if etag.is_none() {
|
||||||
|
Err(FetchError::BadHeaders("ETag".to_string()))
|
||||||
|
} else if last_modified.is_none() {
|
||||||
|
Err(FetchError::BadHeaders("Last-Modified".to_string()))
|
||||||
|
} else if date.is_none() {
|
||||||
|
Err(FetchError::BadHeaders("Date".to_string()))
|
||||||
} else if content_type.unwrap() != "application/vnd.ms-excel" {
|
} else if content_type.unwrap() != "application/vnd.ms-excel" {
|
||||||
Err(FetchError::BadContentType)
|
Err(FetchError::BadContentType(
|
||||||
|
content_type.unwrap().to_str().unwrap().to_string(),
|
||||||
|
))
|
||||||
} else {
|
} else {
|
||||||
let etag = etag.unwrap().to_str().unwrap().to_string();
|
let etag = etag.unwrap().to_str().unwrap().to_string();
|
||||||
let last_modified =
|
let last_modified =
|
||||||
@@ -49,13 +59,16 @@ async fn fetch_specified(url: &String, user_agent: String, head: bool) -> FetchR
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(_) => Err(FetchError::Unknown),
|
Err(error) => Err(FetchError::Unknown(Arc::new(error))),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl BasicXlsDownloader {
|
impl BasicXlsDownloader {
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
BasicXlsDownloader { url: None }
|
BasicXlsDownloader {
|
||||||
|
url: None,
|
||||||
|
user_agent: env::var("REQWEST_USER_AGENT").expect("USER_AGENT must be set"),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -64,17 +77,12 @@ impl XLSDownloader for BasicXlsDownloader {
|
|||||||
if self.url.is_none() {
|
if self.url.is_none() {
|
||||||
Err(FetchError::NoUrlProvided)
|
Err(FetchError::NoUrlProvided)
|
||||||
} else {
|
} else {
|
||||||
fetch_specified(
|
fetch_specified(self.url.as_ref().unwrap(), &self.user_agent, head).await
|
||||||
self.url.as_ref().unwrap(),
|
|
||||||
"t.me/polytechnic_next".to_string(),
|
|
||||||
head,
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn set_url(&mut self, url: String) -> FetchResult {
|
async fn set_url(&mut self, url: String) -> FetchResult {
|
||||||
let result = fetch_specified(&url, "t.me/polytechnic_next".to_string(), true).await;
|
let result = fetch_specified(&url, &self.user_agent, true).await;
|
||||||
|
|
||||||
if let Ok(_) = result {
|
if let Ok(_) = result {
|
||||||
self.url = Some(url);
|
self.url = Some(url);
|
||||||
@@ -86,7 +94,7 @@ impl XLSDownloader for BasicXlsDownloader {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use crate::xls_downloader::basic_impl::{BasicXlsDownloader, fetch_specified};
|
use crate::xls_downloader::basic_impl::{fetch_specified, BasicXlsDownloader};
|
||||||
use crate::xls_downloader::interface::{FetchError, XLSDownloader};
|
use crate::xls_downloader::interface::{FetchError, XLSDownloader};
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
@@ -95,8 +103,8 @@ mod tests {
|
|||||||
let user_agent = String::new();
|
let user_agent = String::new();
|
||||||
|
|
||||||
let results = [
|
let results = [
|
||||||
fetch_specified(&url, user_agent.clone(), true).await,
|
fetch_specified(&url, &user_agent, true).await,
|
||||||
fetch_specified(&url, user_agent.clone(), false).await,
|
fetch_specified(&url, &user_agent, false).await,
|
||||||
];
|
];
|
||||||
|
|
||||||
assert!(results[0].is_err());
|
assert!(results[0].is_err());
|
||||||
@@ -109,21 +117,17 @@ mod tests {
|
|||||||
let user_agent = String::new();
|
let user_agent = String::new();
|
||||||
|
|
||||||
let results = [
|
let results = [
|
||||||
fetch_specified(&url, user_agent.clone(), true).await,
|
fetch_specified(&url, &user_agent, true).await,
|
||||||
fetch_specified(&url, user_agent.clone(), false).await,
|
fetch_specified(&url, &user_agent, false).await,
|
||||||
];
|
];
|
||||||
|
|
||||||
assert!(results[0].is_err());
|
assert!(results[0].is_err());
|
||||||
assert!(results[1].is_err());
|
assert!(results[1].is_err());
|
||||||
|
|
||||||
assert_eq!(
|
let expected_error = FetchError::BadStatusCode(404);
|
||||||
*results[0].as_ref().err().unwrap(),
|
|
||||||
FetchError::BadStatusCode
|
assert_eq!(*results[0].as_ref().err().unwrap(), expected_error);
|
||||||
);
|
assert_eq!(*results[1].as_ref().err().unwrap(), expected_error);
|
||||||
assert_eq!(
|
|
||||||
*results[1].as_ref().err().unwrap(),
|
|
||||||
FetchError::BadStatusCode
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
@@ -132,15 +136,17 @@ mod tests {
|
|||||||
let user_agent = String::new();
|
let user_agent = String::new();
|
||||||
|
|
||||||
let results = [
|
let results = [
|
||||||
fetch_specified(&url, user_agent.clone(), true).await,
|
fetch_specified(&url, &user_agent, true).await,
|
||||||
fetch_specified(&url, user_agent.clone(), false).await,
|
fetch_specified(&url, &user_agent, false).await,
|
||||||
];
|
];
|
||||||
|
|
||||||
assert!(results[0].is_err());
|
assert!(results[0].is_err());
|
||||||
assert!(results[1].is_err());
|
assert!(results[1].is_err());
|
||||||
|
|
||||||
assert_eq!(*results[0].as_ref().err().unwrap(), FetchError::BadHeaders);
|
let expected_error = FetchError::BadHeaders("ETag".to_string());
|
||||||
assert_eq!(*results[1].as_ref().err().unwrap(), FetchError::BadHeaders);
|
|
||||||
|
assert_eq!(*results[0].as_ref().err().unwrap(), expected_error);
|
||||||
|
assert_eq!(*results[1].as_ref().err().unwrap(), expected_error);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
@@ -149,21 +155,12 @@ mod tests {
|
|||||||
let user_agent = String::new();
|
let user_agent = String::new();
|
||||||
|
|
||||||
let results = [
|
let results = [
|
||||||
fetch_specified(&url, user_agent.clone(), true).await,
|
fetch_specified(&url, &user_agent, true).await,
|
||||||
fetch_specified(&url, user_agent.clone(), false).await,
|
fetch_specified(&url, &user_agent, false).await,
|
||||||
];
|
];
|
||||||
|
|
||||||
assert!(results[0].is_err());
|
assert!(results[0].is_err());
|
||||||
assert!(results[1].is_err());
|
assert!(results[1].is_err());
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
*results[0].as_ref().err().unwrap(),
|
|
||||||
FetchError::BadContentType
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
*results[1].as_ref().err().unwrap(),
|
|
||||||
FetchError::BadContentType
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
@@ -172,8 +169,8 @@ mod tests {
|
|||||||
let user_agent = String::new();
|
let user_agent = String::new();
|
||||||
|
|
||||||
let results = [
|
let results = [
|
||||||
fetch_specified(&url, user_agent.clone(), true).await,
|
fetch_specified(&url, &user_agent, true).await,
|
||||||
fetch_specified(&url, user_agent.clone(), false).await,
|
fetch_specified(&url, &user_agent, false).await,
|
||||||
];
|
];
|
||||||
|
|
||||||
assert!(results[0].is_ok());
|
assert!(results[0].is_ok());
|
||||||
|
|||||||
@@ -1,41 +1,57 @@
|
|||||||
use chrono::{DateTime, Utc};
|
use chrono::{DateTime, Utc};
|
||||||
|
use derive_more::Display;
|
||||||
|
use std::mem::discriminant;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use utoipa::ToSchema;
|
||||||
|
|
||||||
/// Ошибки получения данных XLS
|
/// XLS data retrieval errors.
|
||||||
#[derive(PartialEq, Debug)]
|
#[derive(Clone, Debug, ToSchema, Display)]
|
||||||
pub enum FetchError {
|
pub enum FetchError {
|
||||||
/// Не установлена ссылка на файл
|
/// File url is not set.
|
||||||
|
#[display("The link to the timetable was not provided earlier.")]
|
||||||
NoUrlProvided,
|
NoUrlProvided,
|
||||||
|
|
||||||
/// Неизвестная ошибка
|
/// Unknown error.
|
||||||
Unknown,
|
#[display("An unknown error occurred while downloading the file.")]
|
||||||
|
#[schema(value_type = String)]
|
||||||
|
Unknown(Arc<reqwest::Error>),
|
||||||
|
|
||||||
/// Сервер вернул статус код отличающийся от 200
|
/// Server returned a status code different from 200.
|
||||||
BadStatusCode,
|
#[display("Server returned a status code {_0}.")]
|
||||||
|
BadStatusCode(u16),
|
||||||
|
|
||||||
/// Ссылка ведёт на файл другого типа
|
/// The url leads to a file of a different type.
|
||||||
BadContentType,
|
#[display("The link leads to a file of type '{_0}'.")]
|
||||||
|
BadContentType(String),
|
||||||
|
|
||||||
/// Сервер не вернул ожидаемые заголовки
|
/// Server doesn't return expected headers.
|
||||||
BadHeaders,
|
#[display("Server doesn't return expected header(s) '{_0}'.")]
|
||||||
|
BadHeaders(String),
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Результат получения данных XLS
|
impl PartialEq for FetchError {
|
||||||
|
fn eq(&self, other: &Self) -> bool {
|
||||||
|
discriminant(self) == discriminant(other)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Result of XLS data retrieval.
|
||||||
pub struct FetchOk {
|
pub struct FetchOk {
|
||||||
/// ETag объекта
|
/// ETag object.
|
||||||
pub etag: String,
|
pub etag: String,
|
||||||
|
|
||||||
/// Дата загрузки файла
|
/// File upload date.
|
||||||
pub uploaded_at: DateTime<Utc>,
|
pub uploaded_at: DateTime<Utc>,
|
||||||
|
|
||||||
/// Дата получения данных
|
/// Date data received.
|
||||||
pub requested_at: DateTime<Utc>,
|
pub requested_at: DateTime<Utc>,
|
||||||
|
|
||||||
/// Данные файла
|
/// File data.
|
||||||
pub data: Option<Vec<u8>>,
|
pub data: Option<Vec<u8>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl FetchOk {
|
impl FetchOk {
|
||||||
/// Результат без контента файла
|
/// Result without file content.
|
||||||
pub fn head(etag: String, uploaded_at: DateTime<Utc>) -> Self {
|
pub fn head(etag: String, uploaded_at: DateTime<Utc>) -> Self {
|
||||||
FetchOk {
|
FetchOk {
|
||||||
etag,
|
etag,
|
||||||
@@ -45,7 +61,7 @@ impl FetchOk {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Полный результат
|
/// Full result.
|
||||||
pub fn get(etag: String, uploaded_at: DateTime<Utc>, data: Vec<u8>) -> Self {
|
pub fn get(etag: String, uploaded_at: DateTime<Utc>, data: Vec<u8>) -> Self {
|
||||||
FetchOk {
|
FetchOk {
|
||||||
etag,
|
etag,
|
||||||
@@ -59,9 +75,9 @@ impl FetchOk {
|
|||||||
pub type FetchResult = Result<FetchOk, FetchError>;
|
pub type FetchResult = Result<FetchOk, FetchError>;
|
||||||
|
|
||||||
pub trait XLSDownloader {
|
pub trait XLSDownloader {
|
||||||
/// Получение данных о файле, и, опционально, его контент
|
/// Get data about the file, and optionally its content.
|
||||||
async fn fetch(&self, head: bool) -> FetchResult;
|
async fn fetch(&self, head: bool) -> FetchResult;
|
||||||
|
|
||||||
/// Установка ссылки на файл
|
/// Setting the file link.
|
||||||
async fn set_url(&mut self, url: String) -> FetchResult;
|
async fn set_url(&mut self, url: String) -> FetchResult;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user