1 Commits

Author SHA1 Message Date
dependabot[bot]
e4fd7066d8 Bump tokio from 1.44.1 to 1.44.2
Bumps [tokio](https://github.com/tokio-rs/tokio) from 1.44.1 to 1.44.2.
- [Release notes](https://github.com/tokio-rs/tokio/releases)
- [Commits](https://github.com/tokio-rs/tokio/compare/tokio-1.44.1...tokio-1.44.2)

---
updated-dependencies:
- dependency-name: tokio
  dependency-version: 1.44.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-04-16 21:16:18 +00:00
28 changed files with 494 additions and 805 deletions

View File

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

View File

@@ -1,9 +1,10 @@
name: cargo test
name: Tests
on:
push:
branches: [ "master" ]
tags-ignore: [ "release/v*" ]
pull_request:
branches: [ "master" ]
permissions:
contents: read
@@ -29,4 +30,3 @@ jobs:
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)"

View File

@@ -4,10 +4,9 @@
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/lib/schedule_parser/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/benches" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/actix-macros/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/actix-test/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/schedule-parser/benches" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/schedule-parser/src" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/actix-macros/target" />
<excludeFolder url="file://$MODULE_DIR$/actix-test/target" />
<excludeFolder url="file://$MODULE_DIR$/target" />

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

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

158
Cargo.lock generated
View File

@@ -696,15 +696,6 @@ version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1cb3c4a0d3776f7535c32793be81d6d5fec0d48ac70955d9834e643aa249a52f"
[[package]]
name = "convert_case"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bb402b8d4c85569410425650ce3eddc7d698ed96d39a73f941b08fb63082f1e7"
dependencies = [
"unicode-segmentation",
]
[[package]]
name = "cookie"
version = "0.16.2"
@@ -762,22 +753,25 @@ dependencies = [
[[package]]
name = "criterion"
version = "0.6.0"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bf7af66b0989381bd0be551bd7cc91912a655a58c6918420c9527b1fd8b4679"
checksum = "f2b12d017a929603d80db1831cd3a24082f8137ce19c69e6447f54f5fc8d692f"
dependencies = [
"anes",
"cast",
"ciborium",
"clap",
"criterion-plot",
"itertools 0.13.0",
"is-terminal",
"itertools",
"num-traits",
"once_cell",
"oorandom",
"plotters",
"rayon",
"regex",
"serde",
"serde_derive",
"serde_json",
"tinytemplate",
"walkdir",
@@ -790,7 +784,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b50826342786a51a89e2da3a28f1c32b06e387201bc2d19791f622c673706b1"
dependencies = [
"cast",
"itertools 0.10.5",
"itertools",
]
[[package]]
@@ -924,7 +918,6 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bda628edc44c4bb645fbe0f758797143e4e07926f7ebf4e9bdfbd3d2ce621df3"
dependencies = [
"convert_case",
"proc-macro2",
"quote",
"syn 2.0.100",
@@ -1411,6 +1404,12 @@ version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "hermit-abi"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fbd780fe5cc30f81464441920d82ac8740e2e46b29a6fad543ddd075229ce37e"
[[package]]
name = "hex"
version = "0.4.3"
@@ -1849,6 +1848,17 @@ version = "2.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "469fb0b9cefa57e3ef31275ee7cacb78f2fdca44e4765491884a2b119d4eb130"
[[package]]
name = "is-terminal"
version = "0.4.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e04d7f318608d35d4b61ddd75cbdaee86b023ebe2bd5a66ee0915f0bf93095a9"
dependencies = [
"hermit-abi",
"libc",
"windows-sys 0.59.0",
]
[[package]]
name = "is_terminal_polyfill"
version = "1.70.1"
@@ -1864,15 +1874,6 @@ dependencies = [
"either",
]
[[package]]
name = "itertools"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
dependencies = [
"either",
]
[[package]]
name = "itoa"
version = "1.0.15"
@@ -2395,7 +2396,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a56d757972c98b346a9b766e3f02746cde6dd1cd1d1d563472929fdd74bec4d"
dependencies = [
"anyhow",
"itertools 0.10.5",
"itertools",
"proc-macro2",
"quote",
"syn 2.0.100",
@@ -2440,7 +2441,7 @@ dependencies = [
"rustc-hash",
"rustls",
"socket2",
"thiserror",
"thiserror 2.0.12",
"tokio",
"tracing",
"web-time",
@@ -2460,7 +2461,7 @@ dependencies = [
"rustls",
"rustls-pki-types",
"slab",
"thiserror",
"thiserror 2.0.12",
"tinyvec",
"tracing",
"web-time",
@@ -2873,30 +2874,17 @@ dependencies = [
"windows-sys 0.59.0",
]
[[package]]
name = "schedule-parser"
version = "0.1.0"
dependencies = [
"calamine",
"chrono",
"criterion",
"derive_more",
"fuzzy-matcher",
"regex",
"serde",
"serde_repr",
"utoipa",
]
[[package]]
name = "schedule-parser-rusted"
version = "1.0.5"
version = "0.8.0"
dependencies = [
"actix-macros 0.1.0",
"actix-test",
"actix-web",
"bcrypt",
"calamine",
"chrono",
"criterion",
"derive_more",
"diesel",
"diesel-derive-enum",
@@ -2904,17 +2892,19 @@ dependencies = [
"env_logger",
"firebase-messaging-rs",
"futures-util",
"fuzzy-matcher",
"hex",
"jsonwebtoken",
"mime",
"objectid",
"rand 0.9.0",
"regex",
"reqwest",
"schedule-parser",
"sentry",
"sentry-actix",
"serde",
"serde_json",
"serde_repr",
"serde_with",
"sha1 0.11.0-pre.5",
"tokio",
@@ -2987,14 +2977,13 @@ checksum = "56e6fa9c48d24d85fb3de5ad847117517440f6beceb7798af16b4a87d616b8d0"
[[package]]
name = "sentry"
version = "0.38.1"
version = "0.37.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a505499b38861edd82b5a688fa06ba4ba5875bb832adeeeba22b7b23fc4bc39a"
checksum = "255914a8e53822abd946e2ce8baa41d4cded6b8e938913b7f7b9da5b7ab44335"
dependencies = [
"httpdate",
"native-tls",
"reqwest",
"sentry-actix",
"sentry-backtrace",
"sentry-contexts",
"sentry-core",
@@ -3007,9 +2996,9 @@ dependencies = [
[[package]]
name = "sentry-actix"
version = "0.38.1"
version = "0.37.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39ad8bfdcfbc6e0d0dacaa5728555085ef459fa9226cfc2fe64eefa4b8038b7f"
checksum = "a927aed43cce0e9240f7477ac81cdfa2ffb048e0e2b17000eb5976e14f063993"
dependencies = [
"actix-http",
"actix-web",
@@ -3020,20 +3009,21 @@ dependencies = [
[[package]]
name = "sentry-backtrace"
version = "0.38.1"
version = "0.37.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8dace796060e4ad10e3d1405b122ae184a8b2e71dce05ae450e4f81b7686b0d9"
checksum = "00293cd332a859961f24fd69258f7e92af736feaeb91020cff84dac4188a4302"
dependencies = [
"backtrace",
"once_cell",
"regex",
"sentry-core",
]
[[package]]
name = "sentry-contexts"
version = "0.38.1"
version = "0.37.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "87bd9e6b51ffe2bc7188ebe36cb67557cb95749c08a3f81f33e8c9b135e0d1bc"
checksum = "961990f9caa76476c481de130ada05614cd7f5aa70fb57c2142f0e09ad3fb2aa"
dependencies = [
"hostname 0.4.1",
"libc",
@@ -3045,11 +3035,12 @@ dependencies = [
[[package]]
name = "sentry-core"
version = "0.38.1"
version = "0.37.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7426d4beec270cfdbb50f85f0bb2ce176ea57eed0b11741182a163055a558187"
checksum = "1a6409d845707d82415c800290a5d63be5e3df3c2e417b0997c60531dfbd35ef"
dependencies = [
"rand 0.9.0",
"once_cell",
"rand 0.8.5",
"sentry-types",
"serde",
"serde_json",
@@ -3057,19 +3048,20 @@ dependencies = [
[[package]]
name = "sentry-debug-images"
version = "0.38.1"
version = "0.37.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9df15c066c04f34c4dfd496a8e76590106b93283f72ef1a47d8fb24d88493424"
checksum = "71ab5df4f3b64760508edfe0ba4290feab5acbbda7566a79d72673065888e5cc"
dependencies = [
"findshlibs",
"once_cell",
"sentry-core",
]
[[package]]
name = "sentry-panic"
version = "0.38.1"
version = "0.37.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c92beed69b776a162b6d269bef1eaa3e614090b6df45a88d9b239c4fdbffdfba"
checksum = "609b1a12340495ce17baeec9e08ff8ed423c337c1a84dffae36a178c783623f3"
dependencies = [
"sentry-backtrace",
"sentry-core",
@@ -3077,9 +3069,9 @@ dependencies = [
[[package]]
name = "sentry-tracing"
version = "0.38.1"
version = "0.37.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "55c323492795de90824f3198562e33dd74ae3bc852fbb13c0cabec54a1cf73cd"
checksum = "49f4e86402d5c50239dc7d8fd3f6d5e048221d5fcb4e026d8d50ab57fe4644cb"
dependencies = [
"sentry-backtrace",
"sentry-core",
@@ -3089,16 +3081,16 @@ dependencies = [
[[package]]
name = "sentry-types"
version = "0.38.1"
version = "0.37.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04b6c9287202294685cb1f749b944dbbce8160b81a1061ecddc073025fed129f"
checksum = "3d3f117b8755dbede8260952de2aeb029e20f432e72634e8969af34324591631"
dependencies = [
"debugid",
"hex",
"rand 0.9.0",
"rand 0.8.5",
"serde",
"serde_json",
"thiserror",
"thiserror 1.0.69",
"time 0.3.40",
"url",
"uuid",
@@ -3240,7 +3232,7 @@ checksum = "297f631f50729c8c99b84667867963997ec0b50f32b2a7dbcab828ef0541e8bb"
dependencies = [
"num-bigint",
"num-traits",
"thiserror",
"thiserror 2.0.12",
"time 0.3.40",
]
@@ -3363,13 +3355,33 @@ dependencies = [
"windows-sys 0.59.0",
]
[[package]]
name = "thiserror"
version = "1.0.69"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"
dependencies = [
"thiserror-impl 1.0.69",
]
[[package]]
name = "thiserror"
version = "2.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "567b8a2dae586314f7be2a752ec7474332959c6460e02bde30d702a66d488708"
dependencies = [
"thiserror-impl",
"thiserror-impl 2.0.12",
]
[[package]]
name = "thiserror-impl"
version = "1.0.69"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.100",
]
[[package]]
@@ -3472,9 +3484,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]]
name = "tokio"
version = "1.44.1"
version = "1.44.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f382da615b842244d4b8738c82ed1275e6c5dd90c459a30941cd07080b06c91a"
checksum = "e6b88822cbe49de4185e3a4cbf8321dd487cf5fe0c5c65695fef6346371e9c48"
dependencies = [
"backtrace",
"bytes",
@@ -3710,12 +3722,6 @@ version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512"
[[package]]
name = "unicode-segmentation"
version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6ccf251212114b54433ec949fd6a7841275f9ada20dddd2f29e9ceea4501493"
[[package]]
name = "unicode-xid"
version = "0.2.6"
@@ -4361,7 +4367,7 @@ dependencies = [
"flate2",
"indexmap 2.8.0",
"memchr",
"thiserror",
"thiserror 2.0.12",
"zopfli",
]

View File

@@ -1,40 +1,40 @@
[workspace]
members = ["actix-macros", "actix-test", "schedule-parser"]
members = ["actix-macros", "actix-test"]
[package]
name = "schedule-parser-rusted"
version = "1.0.5"
version = "0.8.0"
edition = "2024"
publish = false
[profile.release]
debug = true
[dependencies]
actix-web = "4.10.2"
actix-macros = { path = "actix-macros" }
schedule-parser = { path = "schedule-parser", features = ["test-utils"] }
bcrypt = "0.17.0"
calamine = "0.26.1"
chrono = { version = "0.4.40", features = ["serde"] }
derive_more = { version = "2", features = ["full"] }
derive_more = "2.0.1"
diesel = { version = "2.2.8", features = ["postgres"] }
diesel-derive-enum = { git = "https://github.com/Havunen/diesel-derive-enum.git", features = ["postgres"] }
dotenvy = "0.15.7"
env_logger = "0.11.7"
firebase-messaging-rs = { git = "https://github.com/i10416/firebase-messaging-rs.git" }
futures-util = "0.3.31"
fuzzy-matcher = "0.3.7"
jsonwebtoken = { version = "9.3.1", features = ["use_pem"] }
hex = "0.4.3"
mime = "0.3.17"
objectid = "0.2.0"
regex = "1.11.1"
reqwest = { version = "0.12.15", features = ["json"] }
sentry = "0.38"
sentry-actix = "0.38"
sentry = "0.37.0"
sentry-actix = "0.37.0"
serde = { version = "1.0.219", features = ["derive"] }
serde_json = "1.0.140"
serde_with = "3.12.0"
serde_repr = "0.1.20"
sha1 = "0.11.0-pre.5"
tokio = { version = "1.44.1", features = ["macros", "rt-multi-thread"] }
tokio = { version = "1.44.2", features = ["macros", "rt-multi-thread"] }
rand = "0.9.0"
utoipa = { version = "5", features = ["actix_extras", "chrono"] }
utoipa-rapidoc = { version = "6.0.0", features = ["actix-web"] }
@@ -43,3 +43,8 @@ uuid = { version = "1.16.0", features = ["v4"] }
[dev-dependencies]
actix-test = { path = "actix-test" }
criterion = "0.5.1"
[[bench]]
name = "parse"
harness = false

View File

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

View File

@@ -1,9 +1,9 @@
use criterion::{Criterion, criterion_group, criterion_main};
use schedule_parser::parse_xls;
use schedule_parser_rusted::parser::parse_xls;
pub fn bench_parse_xls(c: &mut Criterion) {
let buffer: Vec<u8> = include_bytes!("../../schedule.xls").to_vec();
let buffer: Vec<u8> = include_bytes!("../schedule.xls").to_vec();
c.bench_function("parse_xls", |b| b.iter(|| parse_xls(&buffer).unwrap()));
}

View File

@@ -1,24 +0,0 @@
[package]
name = "schedule-parser"
version = "0.1.0"
edition = "2024"
[features]
test-utils = []
[dependencies]
calamine = "0.26"
chrono = { version = "0.4", features = ["serde"] }
derive_more = { version = "2", features = ["full"] }
serde = { version = "1.0.219", features = ["derive"] }
serde_repr = "0.1.20"
fuzzy-matcher = "0.3.7"
regex = "1.11.1"
utoipa = { version = "5", features = ["chrono"] }
[dev-dependencies]
criterion = "0.6"
[[bench]]
name = "parse"
harness = false

View File

@@ -1,25 +0,0 @@
#[macro_export]
macro_rules! or_continue {
( $e:expr ) => {
{
if let Some(x) = $e {
x
} else {
continue;
}
}
}
}
#[macro_export]
macro_rules! or_break {
( $e:expr ) => {
{
if let Some(x) = $e {
x
} else {
break;
}
}
}
}

Binary file not shown.

View File

@@ -1,4 +1,4 @@
use schedule_parser::schema::ParseResult;
use crate::parser::schema::ParseResult;
use crate::utility::hasher::DigestHasher;
use crate::xls_downloader::basic_impl::BasicXlsDownloader;
use actix_web::web;

1
src/lib.rs Normal file
View File

@@ -0,0 +1 @@
pub mod parser;

View File

@@ -13,6 +13,7 @@ mod app_state;
mod database;
mod parser;
mod xls_downloader;
mod extractors;
@@ -111,6 +112,8 @@ fn main() -> io::Result<()> {
},
));
unsafe { std::env::set_var("RUST_BACKTRACE", "1") };
dotenv().unwrap();
env_logger::init();

View File

@@ -1,7 +1,7 @@
use crate::LessonParseResult::{Lessons, Street};
use crate::schema::LessonType::Break;
use crate::schema::{
Day, ErrorCell, ErrorCellPos, Lesson, LessonBoundaries, LessonSubGroup, LessonType, ParseError,
use crate::parser::LessonParseResult::{Lessons, Street};
use crate::parser::schema::LessonType::Break;
use crate::parser::schema::{
Day, ErrorCell, ErrorCellPos, Lesson, LessonSubGroup, LessonTime, LessonType, ParseError,
ParseResult, ScheduleEntry,
};
use calamine::{Reader, Xls, open_workbook_from_rs};
@@ -11,14 +11,15 @@ use fuzzy_matcher::skim::SkimMatcherV2;
use regex::Regex;
use std::collections::HashMap;
use std::io::Cursor;
use std::ops::Deref;
use std::sync::LazyLock;
mod macros;
pub mod schema;
/// Data cell storing the group name.
struct GroupCellInfo {
/// Data cell storing the line.
struct InternalId {
/// Line index.
row: u32,
/// Column index.
column: u32,
@@ -26,25 +27,10 @@ struct GroupCellInfo {
name: String,
}
/// Data cell storing the line.
struct DayCellInfo {
/// Line index.
row: u32,
/// Column index.
column: u32,
/// Day name.
name: String,
/// Date of the day.
date: DateTime<Utc>,
}
/// Data on the time of lessons from the second column of the schedule.
struct BoundariesCellInfo {
struct InternalTime {
/// Temporary segment of the lesson.
time_range: LessonBoundaries,
time_range: LessonTime,
/// Type of lesson.
lesson_type: LessonType,
@@ -56,18 +42,8 @@ struct BoundariesCellInfo {
xls_range: ((u32, u32), (u32, u32)),
}
struct WorkSheet {
pub data: calamine::Range<calamine::Data>,
pub merges: Vec<calamine::Dimensions>,
}
impl Deref for WorkSheet {
type Target = calamine::Range<calamine::Data>;
fn deref(&self) -> &Self::Target {
&self.data
}
}
/// Working sheet type alias.
type WorkSheet = calamine::Range<calamine::Data>;
/// Getting a line from the required cell.
fn get_string_from_cell(worksheet: &WorkSheet, row: u32, col: u32) -> Option<String> {
@@ -98,69 +74,92 @@ 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)) {
return match worksheet
.merges
.iter()
.find(|merge| merge.start.0 == row && merge.start.1 == column)
{
Some(merge) => (merge.start, (merge.end.0 + 1, merge.end.1 + 1)),
None => ((row, column), (row + 1, column + 1))
let worksheet_end = worksheet.end().unwrap();
let row_end: u32 = {
let mut r: u32 = 0;
for _r in (row + 1)..worksheet_end.0 {
r = _r;
if let Some(_) = worksheet.get((_r as usize, column as usize)) {
break;
}
}
r
};
let column_end: u32 = {
let mut c: u32 = 0;
for _c in (column + 1)..worksheet_end.1 {
c = _c;
if let Some(_) = worksheet.get((row as usize, _c as usize)) {
break;
}
}
c
};
((row, column), (row_end, column_end))
}
/// Obtaining a "skeleton" schedule from the working sheet.
fn parse_skeleton(
worksheet: &WorkSheet,
) -> Result<(Vec<DayCellInfo>, Vec<GroupCellInfo>), ParseError> {
let mut groups: Vec<GroupCellInfo> = Vec::new();
let mut days: Vec<DayCellInfo> = Vec::new();
fn parse_skeleton(worksheet: &WorkSheet) -> Result<(Vec<InternalId>, Vec<InternalId>), ParseError> {
let range = &worksheet;
let worksheet_start = worksheet.start().ok_or(ParseError::UnknownWorkSheetRange)?;
let worksheet_end = worksheet.end().ok_or(ParseError::UnknownWorkSheetRange)?;
let mut is_parsed = false;
let mut row = worksheet_start.0;
let mut groups: Vec<InternalId> = Vec::new();
let mut days: Vec<InternalId> = Vec::new();
while row < worksheet_end.0 {
let start = range.start().ok_or(ParseError::UnknownWorkSheetRange)?;
let end = range.end().ok_or(ParseError::UnknownWorkSheetRange)?;
let mut row = start.0;
while row < end.0 {
row += 1;
let day_full_name = or_continue!(get_string_from_cell(&worksheet, row, 0));
let day_name_opt = get_string_from_cell(&worksheet, row, 0);
if day_name_opt.is_none() {
continue;
}
let day_name = day_name_opt.unwrap();
if !is_parsed {
is_parsed = true;
// parse groups row when days column will found
if groups.is_empty() {
// переход на предыдущую строку
row -= 1;
for column in (worksheet_start.1 + 2)..=worksheet_end.1 {
groups.push(GroupCellInfo {
for column in (start.1 + 2)..=end.1 {
let group_name = get_string_from_cell(&worksheet, row, column);
if group_name.is_none() {
continue;
}
groups.push(InternalId {
row,
column,
name: or_continue!(get_string_from_cell(&worksheet, row, column)),
name: group_name.unwrap(),
});
}
// возврат на текущую строку
row += 1;
}
let (day_name, day_date) = {
let space_index = day_full_name.find(' ').unwrap();
let name = day_full_name[..space_index].to_string();
let date_raw = day_full_name[space_index + 1..].to_string();
let date_add = format!("{} 00:00:00", date_raw);
let date =
or_break!(NaiveDateTime::parse_from_str(&*date_add, "%d.%m.%Y %H:%M:%S").ok());
(name, date.and_utc())
};
days.push(DayCellInfo {
days.push(InternalId {
row,
column: 0,
name: day_name,
date: day_date,
name: day_name.clone(),
});
if days.len() > 2 && day_name.starts_with("Суббота") {
break;
}
}
Ok((days, groups))
@@ -239,80 +238,75 @@ fn guess_lesson_type(name: &String) -> Option<(String, LessonType)> {
fn parse_lesson(
worksheet: &WorkSheet,
day: &mut Day,
day_boundaries: &Vec<BoundariesCellInfo>,
lesson_boundaries: &BoundariesCellInfo,
day_times: &Vec<InternalTime>,
time: &InternalTime,
column: u32,
) -> Result<LessonParseResult, ParseError> {
let row = lesson_boundaries.xls_range.0.0;
let row = time.xls_range.0.0;
let (name, lesson_type) = {
let full_name = match get_string_from_cell(&worksheet, row, column) {
Some(x) => x,
None => return Ok(Lessons(Vec::new())),
};
let raw_name_opt = get_string_from_cell(&worksheet, row, column);
if raw_name_opt.is_none() {
return Ok(Lessons(Vec::new()));
}
let raw_name = raw_name_opt.unwrap();
static OTHER_STREET_RE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^[А-Я][а-я]+,?\s?[0-9]+$").unwrap());
if OTHER_STREET_RE.is_match(&full_name) {
return Ok(Street(full_name));
if OTHER_STREET_RE.is_match(&raw_name) {
return Ok(Street(raw_name));
}
match guess_lesson_type(&full_name) {
Some(x) => x,
None => (full_name, lesson_boundaries.lesson_type.clone()),
if let Some(guess) = guess_lesson_type(&raw_name) {
guess
} else {
(raw_name, time.lesson_type.clone())
}
};
let (default_range, lesson_time) = {
let (default_range, lesson_time) = || -> Result<(Option<[u8; 2]>, LessonTime), ParseError> {
// check if multi-lesson
let cell_range = get_merge_from_start(worksheet, row, column);
let end_time_arr = day_boundaries
let end_time_arr = day_times
.iter()
.filter(|time| time.xls_range.1.0 == cell_range.1.0)
.collect::<Vec<&BoundariesCellInfo>>();
.collect::<Vec<&InternalTime>>();
let end_time = end_time_arr
.first()
.ok_or(ParseError::LessonTimeNotFound(ErrorCellPos { row, column }))?;
let range: Option<[u8; 2]> = if lesson_boundaries.default_index != None {
let default = lesson_boundaries.default_index.unwrap() as u8;
let range: Option<[u8; 2]> = if time.default_index != None {
let default = time.default_index.unwrap() as u8;
Some([default, end_time.default_index.unwrap() as u8])
} else {
None
};
let time = LessonBoundaries {
start: lesson_boundaries.time_range.start,
let time = LessonTime {
start: time.time_range.start,
end: end_time.time_range.end,
};
Ok((range, time))
}?;
}()?;
let (name, mut subgroups) = parse_name_and_subgroups(&name)?;
{
let cabinets: Vec<String> = parse_cabinets(worksheet, row, column + 1);
match cabinets.len() {
// Если кабинетов нет, но есть подгруппы, назначаем им кабинет "??"
0 => {
// Если количество кабинетов равно 1, назначаем этот кабинет всем подгруппам
if cabinets.len() == 1 {
for subgroup in &mut subgroups {
subgroup.cabinet = Some("??".to_string());
subgroup.cabinet = Some(cabinets.get(0).or(Some(&String::new())).unwrap().clone())
}
}
// Назначаем этот кабинет всем подгруппам
1 => {
for subgroup in &mut subgroups {
subgroup.cabinet =
Some(cabinets.get(0).or(Some(&String::new())).unwrap().clone())
}
}
len => {
// Если количество кабинетов совпадает с количеством подгрупп, назначаем кабинеты по порядку
if len == subgroups.len() {
else if cabinets.len() == subgroups.len() {
for subgroup in &mut subgroups {
subgroup.cabinet = Some(
cabinets
@@ -321,8 +315,9 @@ fn parse_lesson(
.clone(),
);
}
}
// Если количество кабинетов больше количества подгрупп, делаем ещё одну подгруппу.
} else if len > subgroups.len() {
else if cabinets.len() > subgroups.len() {
for index in 0..subgroups.len() {
subgroups[index].cabinet = Some(cabinets[index].clone());
}
@@ -335,8 +330,14 @@ fn parse_lesson(
});
}
}
// Если кабинетов нет, но есть подгруппы, назначаем им значение "??"
else {
for subgroup in &mut subgroups {
subgroup.cabinet = Some("??".to_string());
}
};
}
cabinets
};
let lesson = Lesson {
@@ -348,7 +349,7 @@ fn parse_lesson(
group: None,
};
let prev_lesson = if day.lessons.is_empty() {
let prev_lesson = if day.lessons.len() == 0 {
return Ok(Lessons(Vec::from([lesson])));
} else {
&day.lessons[day.lessons.len() - 1]
@@ -359,7 +360,7 @@ fn parse_lesson(
lesson_type: Break,
default_range: None,
name: None,
time: LessonBoundaries {
time: LessonTime {
start: prev_lesson.time.end,
end: lesson.time.start,
},
@@ -473,122 +474,6 @@ fn parse_name_and_subgroups(name: &String) -> Result<(String, Vec<LessonSubGroup
Ok((lesson_name, subgroups))
}
fn parse_lesson_boundaries_cell(
cell_data: &String,
date: DateTime<Utc>,
) -> Option<LessonBoundaries> {
static TIME_RE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"(\d+\.\d+)-(\d+\.\d+)").unwrap());
let parse_res = if let Some(captures) = TIME_RE.captures(cell_data) {
captures
} else {
return None;
};
let start_match = parse_res.get(1).unwrap().as_str();
let start_parts: Vec<&str> = start_match.split(".").collect();
let end_match = parse_res.get(2).unwrap().as_str();
let end_parts: Vec<&str> = end_match.split(".").collect();
static GET_TIME: fn(DateTime<Utc>, &Vec<&str>) -> DateTime<Utc> = |date, parts| {
date + Duration::hours(parts[0].parse::<i64>().unwrap() - 4)
+ Duration::minutes(parts[1].parse::<i64>().unwrap())
};
Some(LessonBoundaries {
start: GET_TIME(date.clone(), &start_parts),
end: GET_TIME(date, &end_parts),
})
}
fn parse_day_boundaries_column(
worksheet: &WorkSheet,
day_markup: &DayCellInfo,
lesson_time_column: u32,
row_distance: u32,
) -> Result<Vec<BoundariesCellInfo>, ParseError> {
let mut day_times: Vec<BoundariesCellInfo> = Vec::new();
for row in day_markup.row..(day_markup.row + row_distance) {
let time_cell = if let Some(str) = get_string_from_cell(&worksheet, row, lesson_time_column)
{
str
} else {
continue;
};
let lesson_time = parse_lesson_boundaries_cell(&time_cell, day_markup.date.clone()).ok_or(
ParseError::LessonBoundaries(ErrorCell::new(
row,
lesson_time_column,
time_cell.clone(),
)),
)?;
// type
let lesson_type = if time_cell.contains("пара") {
LessonType::Default
} else {
LessonType::Additional
};
// lesson index
let default_index = if lesson_type == LessonType::Default {
Some(
time_cell
.chars()
.next()
.unwrap()
.to_string()
.parse::<u32>()
.unwrap(),
)
} else {
None
};
day_times.push(BoundariesCellInfo {
time_range: lesson_time,
lesson_type,
default_index,
xls_range: get_merge_from_start(&worksheet, row, lesson_time_column),
});
}
return Ok(day_times);
}
fn parse_week_boundaries_column(
worksheet: &WorkSheet,
week_markup: &Vec<DayCellInfo>,
) -> Result<Vec<Vec<BoundariesCellInfo>>, ParseError> {
let mut result: Vec<Vec<BoundariesCellInfo>> = Vec::new();
let worksheet_end_row = worksheet.end().unwrap().0;
let lesson_time_column = week_markup[0].column + 1;
for day_index in 0..week_markup.len() {
let day_markup = &week_markup[day_index];
// Если текущий день не последнему, то индекс строки следующего дня минус индекс строки текущего дня.
// Если текущий день - последний, то индекс последней строки документа минус индекс строки текущего дня.
let row_distance = if day_index != week_markup.len() - 1 {
week_markup[day_index + 1].row
} else {
worksheet_end_row
} - day_markup.row;
let day_boundaries =
parse_day_boundaries_column(&worksheet, day_markup, lesson_time_column, row_distance)?;
result.push(day_boundaries);
}
Ok(result)
}
/// Conversion of the list of couples of groups in the list of lessons of teachers.
fn convert_groups_to_teachers(
groups: &HashMap<String, ScheduleEntry>,
@@ -677,11 +562,11 @@ fn convert_groups_to_teachers(
/// # Examples
///
/// ```
/// use schedule_parser::parse_xls;
/// use schedule_parser_rusted::parser::parse_xls;
///
/// let result = parse_xls(&include_bytes!("../../schedule.xls").to_vec());
///
/// assert!(result.is_ok(), "{}", result.err().unwrap());
/// assert!(result.is_ok());
///
/// assert_ne!(result.as_ref().unwrap().groups.len(), 0);
/// assert_ne!(result.as_ref().unwrap().teachers.len(), 0);
@@ -691,27 +576,19 @@ pub fn parse_xls(buffer: &Vec<u8>) -> Result<ParseResult, ParseError> {
let mut workbook: Xls<_> =
open_workbook_from_rs(cursor).map_err(|e| ParseError::BadXLS(std::sync::Arc::new(e)))?;
let worksheet = {
let (worksheet_name, worksheet) = workbook
let worksheet: WorkSheet = workbook
.worksheets()
.first()
.ok_or(ParseError::NoWorkSheets)?
.clone();
.1
.to_owned();
let worksheet_merges = workbook
.worksheet_merge_cells(&*worksheet_name)
.ok_or(ParseError::NoWorkSheets)?;
WorkSheet {
data: worksheet,
merges: worksheet_merges,
}
};
let (week_markup, groups_markup) = parse_skeleton(&worksheet)?;
let week_boundaries = parse_week_boundaries_column(&worksheet, &week_markup)?;
let (days_markup, groups_markup) = parse_skeleton(&worksheet)?;
let mut groups: HashMap<String, ScheduleEntry> = HashMap::new();
let mut days_times: Vec<Vec<InternalTime>> = Vec::new();
let saturday_end_row = worksheet.end().unwrap().0;
for group_markup in groups_markup {
let mut group = ScheduleEntry {
@@ -719,28 +596,118 @@ pub fn parse_xls(buffer: &Vec<u8>) -> Result<ParseResult, ParseError> {
days: Vec::new(),
};
for day_index in 0..(&week_markup).len() {
let day_markup = &week_markup[day_index];
for day_index in 0..(&days_markup).len() {
let day_markup = &days_markup[day_index];
let mut day = Day {
name: day_markup.name.clone(),
let mut day = {
let space_index = day_markup.name.find(' ').unwrap();
let name = day_markup.name[..space_index].to_string();
let date_raw = day_markup.name[space_index + 1..].to_string();
let date_add = format!("{} 00:00:00", date_raw);
let date = NaiveDateTime::parse_from_str(&*date_add, "%d.%m.%Y %H:%M:%S");
Day {
name,
street: None,
date: day_markup.date,
date: date.unwrap().and_utc(),
lessons: Vec::new(),
}
};
let day_boundaries = &week_boundaries[day_index];
let lesson_time_column = days_markup[0].column + 1;
for lesson_boundaries in day_boundaries {
let row_distance = if day_index != days_markup.len() - 1 {
days_markup[day_index + 1].row
} else {
saturday_end_row
} - day_markup.row;
if days_times.len() != 6 {
let mut day_times: Vec<InternalTime> = Vec::new();
for row in day_markup.row..(day_markup.row + row_distance) {
// time
let time_opt = get_string_from_cell(&worksheet, row, lesson_time_column);
if time_opt.is_none() {
continue;
}
let time = time_opt.unwrap();
// type
let lesson_type = if time.contains("пара") {
LessonType::Default
} else {
LessonType::Additional
};
// lesson index
let default_index = if lesson_type == LessonType::Default {
Some(
time.chars()
.next()
.unwrap()
.to_string()
.parse::<u32>()
.unwrap(),
)
} else {
None
};
// time
let time_range = {
static TIME_RE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"(\d+\.\d+)-(\d+\.\d+)").unwrap());
let parse_res = TIME_RE.captures(&time).ok_or(ParseError::GlobalTime(
ErrorCell::new(row, lesson_time_column, time.clone()),
))?;
let start_match = parse_res.get(1).unwrap().as_str();
let start_parts: Vec<&str> = start_match.split(".").collect();
let end_match = parse_res.get(2).unwrap().as_str();
let end_parts: Vec<&str> = end_match.split(".").collect();
static GET_TIME: fn(DateTime<Utc>, &Vec<&str>) -> DateTime<Utc> =
|date, parts| {
date + Duration::hours(parts[0].parse::<i64>().unwrap() - 4)
+ Duration::minutes(parts[1].parse::<i64>().unwrap())
};
LessonTime {
start: GET_TIME(day.date.clone(), &start_parts),
end: GET_TIME(day.date.clone(), &end_parts),
}
};
day_times.push(InternalTime {
time_range,
lesson_type,
default_index,
xls_range: get_merge_from_start(&worksheet, row, lesson_time_column),
});
}
days_times.push(day_times);
}
let day_times = &days_times[day_index];
for time in day_times {
match &mut parse_lesson(
&worksheet,
&mut day,
&day_boundaries,
&lesson_boundaries,
&day_times,
&time,
group_markup.column,
)? {
Lessons(lesson) => day.lessons.append(lesson),
Street(street) => day.street = Some(street.to_owned()),
Lessons(l) => day.lessons.append(l),
Street(s) => day.street = Some(s.to_owned()),
}
}
@@ -756,39 +723,21 @@ pub fn parse_xls(buffer: &Vec<u8>) -> Result<ParseResult, ParseError> {
})
}
#[cfg(any(test, feature = "test-utils"))]
pub mod test_utils {
#[cfg(test)]
pub mod tests {
use super::*;
pub fn test_result() -> Result<ParseResult, ParseError> {
parse_xls(&include_bytes!("../../schedule.xls").to_vec())
}
}
#[cfg(test)]
pub mod tests {
#[test]
fn read() {
let result = super::test_utils::test_result();
let result = test_result();
assert!(result.is_ok(), "{}", result.err().unwrap());
assert!(result.is_ok());
assert_ne!(result.as_ref().unwrap().groups.len(), 0);
assert_ne!(result.as_ref().unwrap().teachers.len(), 0);
}
#[test]
fn test_split_lesson() {
let result = super::test_utils::test_result();
assert!(result.is_ok(), "{}", result.err().unwrap());
let result = result.unwrap();
assert!(result.groups.contains_key("ИС-214/23"));
let group = result.groups.get("ИС-214/23").unwrap();
let thursday = group.days.get(3).unwrap();
assert_eq!(thursday.lessons.len(), 1);
assert_eq!(thursday.lessons[0].default_range.unwrap()[1], 3);
}
}

View File

@@ -8,7 +8,7 @@ use utoipa::ToSchema;
/// The beginning and end of the lesson.
#[derive(Clone, Hash, Debug, Serialize, Deserialize, ToSchema)]
pub struct LessonBoundaries {
pub struct LessonTime {
/// The beginning of a lesson.
pub start: DateTime<Utc>,
@@ -72,7 +72,7 @@ pub struct Lesson {
pub name: Option<String>,
/// The beginning and end.
pub time: LessonBoundaries,
pub time: LessonTime,
/// List of subgroups.
#[serde(rename = "subGroups")]
@@ -153,9 +153,9 @@ pub enum ParseError {
#[display("There is no data on work sheet boundaries.")]
UnknownWorkSheetRange,
/// Failed to read the beginning and end of the lesson from the cell
#[display("Failed to read lesson start and end from {_0}.")]
LessonBoundaries(ErrorCell),
/// Failed to read the beginning and end of the lesson from the line
#[display("Failed to read lesson start and end times from {_0}.")]
GlobalTime(ErrorCell),
/// Not found the beginning and the end corresponding to the lesson.
#[display("No start and end times matching the lesson (at {_0}) was found.")]
@@ -173,7 +173,7 @@ impl Serialize for ParseError {
ParseError::UnknownWorkSheetRange => {
serializer.serialize_str("UNKNOWN_WORK_SHEET_RANGE")
}
ParseError::LessonBoundaries(_) => serializer.serialize_str("GLOBAL_TIME"),
ParseError::GlobalTime(_) => serializer.serialize_str("GLOBAL_TIME"),
ParseError::LessonTimeNotFound(_) => serializer.serialize_str("LESSON_TIME_NOT_FOUND"),
}
}

View File

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

View File

@@ -71,7 +71,7 @@ pub async fn sign_in_vk(
) -> ServiceResponse {
let data = data_json.into_inner();
match parse_vk_id(&data.access_token, app_state.vk_id.client_id) {
match parse_vk_id(&data.access_token) {
Ok(id) => sign_in_combined(Vk(id), &app_state).await.into(),
Err(_) => ErrorCode::InvalidVkAccessToken.into_response(),
}
@@ -150,7 +150,7 @@ mod tests {
use std::fmt::Write;
async fn sign_in_client(data: Request) -> ServiceResponse {
let app = test_app(test_app_state(Default::default()).await, sign_in).await;
let app = test_app(test_app_state().await, sign_in).await;
let req = test::TestRequest::with_uri("/sign-in")
.method(Method::POST)

View File

@@ -79,7 +79,7 @@ pub async fn sign_up_vk(
) -> ServiceResponse {
let data = data_json.into_inner();
match parse_vk_id(&data.access_token, app_state.vk_id.client_id) {
match parse_vk_id(&data.access_token) {
Ok(id) => sign_up_combined(
SignUpData {
username: data.username,
@@ -241,9 +241,7 @@ mod tests {
use crate::database::models::UserRole;
use crate::routes::auth::sign_up::schema::Request;
use crate::routes::auth::sign_up::sign_up;
use crate::test_env::tests::{
TestAppStateParams, TestScheduleType, static_app_state, test_app_state, test_env,
};
use crate::test_env::tests::{static_app_state, test_app_state, test_env};
use actix_test::test_app;
use actix_web::dev::ServiceResponse;
use actix_web::http::Method;
@@ -254,22 +252,10 @@ mod tests {
username: String,
group: String,
role: UserRole,
load_schedule: bool,
}
async fn sign_up_client(data: SignUpPartial) -> ServiceResponse {
let app = test_app(
test_app_state(TestAppStateParams {
schedule: if data.load_schedule {
TestScheduleType::Local
} else {
TestScheduleType::None
},
})
.await,
sign_up,
)
.await;
let app = test_app(test_app_state().await, sign_up).await;
let req = test::TestRequest::with_uri("/sign-up")
.method(Method::POST)
@@ -300,7 +286,6 @@ mod tests {
username: "test::sign_up_valid".to_string(),
group: "ИС-214/23".to_string(),
role: UserRole::Student,
load_schedule: false,
})
.await;
@@ -320,7 +305,6 @@ mod tests {
username: "test::sign_up_multiple".to_string(),
group: "ИС-214/23".to_string(),
role: UserRole::Student,
load_schedule: false,
})
.await;
@@ -330,7 +314,6 @@ mod tests {
username: "test::sign_up_multiple".to_string(),
group: "ИС-214/23".to_string(),
role: UserRole::Student,
load_schedule: false,
})
.await;
@@ -346,7 +329,6 @@ mod tests {
username: "test::sign_up_invalid_role".to_string(),
group: "ИС-214/23".to_string(),
role: UserRole::Admin,
load_schedule: false,
})
.await;
@@ -362,7 +344,6 @@ mod tests {
username: "test::sign_up_invalid_group".to_string(),
group: "invalid_group".to_string(),
role: UserRole::Student,
load_schedule: true,
})
.await;

View File

@@ -39,7 +39,7 @@ pub async fn group(user: SyncExtractor<User>, app_state: web::Data<AppState>) ->
}
mod schema {
use schedule_parser::schema::ScheduleEntry;
use crate::parser::schema::ScheduleEntry;
use actix_macros::{IntoResponseErrorNamed, StatusCode};
use chrono::{DateTime, NaiveDateTime, Utc};
use derive_more::Display;

View File

@@ -2,9 +2,9 @@ mod cache_status;
mod group;
mod group_names;
mod schedule;
mod schema;
mod teacher;
mod teacher_names;
mod schema;
mod update_download_url;
pub use cache_status::*;

View File

@@ -1,5 +1,5 @@
use crate::app_state::{AppState, Schedule};
use schedule_parser::schema::ScheduleEntry;
use crate::parser::schema::ScheduleEntry;
use actix_macros::{IntoResponseErrorNamed, ResponderJson, StatusCode};
use actix_web::web;
use chrono::{DateTime, Duration, Utc};
@@ -99,7 +99,7 @@ impl From<&Schedule> for CacheStatus {
fn from(value: &Schedule) -> Self {
Self {
cache_hash: value.hash(),
cache_update_required: (Utc::now() - value.fetched_at) > Duration::minutes(5),
cache_update_required: (value.fetched_at - Utc::now()) > Duration::minutes(5),
last_cache_update: value.fetched_at.timestamp(),
last_schedule_update: value.updated_at.timestamp(),
}

View File

@@ -40,7 +40,7 @@ pub async fn teacher(
}
mod schema {
use schedule_parser::schema::ScheduleEntry;
use crate::parser::schema::ScheduleEntry;
use actix_macros::{IntoResponseErrorNamed, StatusCode};
use chrono::{DateTime, NaiveDateTime, Utc};
use derive_more::Display;

View File

@@ -1,10 +1,10 @@
use self::schema::*;
use crate::AppState;
use crate::app_state::Schedule;
use schedule_parser::parse_xls;
use crate::parser::parse_xls;
use crate::routes::schedule::schema::CacheStatus;
use crate::routes::schema::{IntoResponseAsError, ResponseError};
use crate::xls_downloader::interface::{FetchError, XLSDownloader};
use crate::xls_downloader::interface::XLSDownloader;
use actix_web::web::Json;
use actix_web::{patch, web};
use chrono::Utc;
@@ -60,32 +60,29 @@ pub async fn update_download_url(
}
},
Err(error) => {
if let FetchError::Unknown(error) = &error {
sentry::capture_error(&error);
}
eprintln!("Unknown url provided {}", data.url);
eprintln!("{:?}", error);
ErrorCode::DownloadFailed(error).into_response()
ErrorCode::DownloadFailed.into_response()
}
}
}
Err(error) => {
if let FetchError::Unknown(error) = &error {
sentry::capture_error(&error);
}
eprintln!("Unknown url provided {}", data.url);
eprintln!("{:?}", error);
ErrorCode::FetchFailed(error).into_response()
ErrorCode::FetchFailed.into_response()
}
}
}
mod schema {
use schedule_parser::schema::ParseError;
use crate::parser::schema::ParseError;
use crate::routes::schedule::schema::CacheStatus;
use actix_macros::{IntoResponseErrorNamed, StatusCode};
use derive_more::Display;
use serde::{Deserialize, Serialize, Serializer};
use utoipa::ToSchema;
use crate::xls_downloader::interface::FetchError;
pub type ServiceResponse = crate::routes::schema::Response<CacheStatus, ErrorCode>;
@@ -104,12 +101,12 @@ mod schema {
NonWhitelistedHost,
/// Failed to retrieve file metadata.
#[display("Unable to retrieve metadata from the specified URL: {_0}")]
FetchFailed(FetchError),
#[display("Unable to retrieve metadata from the specified URL.")]
FetchFailed,
/// Failed to download the file.
#[display("Unable to retrieve data from the specified URL: {_0}")]
DownloadFailed(FetchError),
#[display("Unable to retrieve data from the specified URL.")]
DownloadFailed,
/// The link leads to an outdated schedule.
///
@@ -130,8 +127,8 @@ mod schema {
{
match self {
ErrorCode::NonWhitelistedHost => serializer.serialize_str("NON_WHITELISTED_HOST"),
ErrorCode::FetchFailed(_) => serializer.serialize_str("FETCH_FAILED"),
ErrorCode::DownloadFailed(_) => serializer.serialize_str("DOWNLOAD_FAILED"),
ErrorCode::FetchFailed => serializer.serialize_str("FETCH_FAILED"),
ErrorCode::DownloadFailed => serializer.serialize_str("DOWNLOAD_FAILED"),
ErrorCode::OutdatedSchedule => serializer.serialize_str("OUTDATED_SCHEDULE"),
ErrorCode::InvalidSchedule(_) => serializer.serialize_str("INVALID_SCHEDULE"),
}

View File

@@ -59,18 +59,15 @@ async fn oauth(data: web::Json<Request>, app_state: web::Data<AppState>) -> Serv
return ErrorCode::VkIdError.into_response();
}
match res.json::<VkIdAuthResponse>().await {
Ok(auth_data) =>
if let Ok(auth_data) = res.json::<VkIdAuthResponse>().await {
Ok(Response {
access_token: auth_data.id_token,
}).into(),
Err(error) => {
sentry::capture_error(&error);
})
.into()
} else {
ErrorCode::VkIdError.into_response()
}
}
}
Err(_) => ErrorCode::VkIdError.into_response(),
}
}

View File

@@ -1,47 +1,24 @@
#[cfg(test)]
pub(crate) mod tests {
use crate::app_state::{AppState, Schedule, app_state};
use schedule_parser::test_utils::test_result;
use crate::utility::mutex::MutexScope;
use crate::parser::tests::test_result;
use actix_web::web;
use std::default::Default;
use tokio::sync::OnceCell;
pub fn test_env() {
dotenvy::from_path(".env.test").expect("Failed to load test environment file");
}
pub enum TestScheduleType {
None,
Local,
}
pub struct TestAppStateParams {
pub schedule: TestScheduleType,
}
impl Default for TestAppStateParams {
fn default() -> Self {
Self {
schedule: TestScheduleType::None,
}
}
}
pub async fn test_app_state(params: TestAppStateParams) -> web::Data<AppState> {
pub async fn test_app_state() -> web::Data<AppState> {
let state = app_state().await;
let mut schedule_lock = state.schedule.lock().unwrap();
state.schedule.scope(|schedule| {
*schedule = match params.schedule {
TestScheduleType::None => None,
TestScheduleType::Local => Some(Schedule {
*schedule_lock = Some(Schedule {
etag: "".to_string(),
fetched_at: Default::default(),
updated_at: Default::default(),
parsed_at: Default::default(),
data: test_result().unwrap(),
}),
}
});
state.clone()
@@ -50,9 +27,6 @@ pub(crate) mod tests {
pub async fn static_app_state() -> web::Data<AppState> {
static STATE: OnceCell<web::Data<AppState>> = OnceCell::const_new();
STATE
.get_or_init(|| test_app_state(Default::default()))
.await
.clone()
STATE.get_or_init(|| test_app_state()).await.clone()
}
}

View File

@@ -1,14 +1,11 @@
use crate::xls_downloader::interface::{FetchError, FetchOk, FetchResult, XLSDownloader};
use chrono::{DateTime, Utc};
use std::env;
use std::sync::Arc;
pub struct BasicXlsDownloader {
pub url: Option<String>,
user_agent: String,
}
async fn fetch_specified(url: &String, user_agent: &String, head: bool) -> FetchResult {
async fn fetch_specified(url: &String, user_agent: String, head: bool) -> FetchResult {
let client = reqwest::Client::new();
let response = if head {
@@ -16,14 +13,14 @@ async fn fetch_specified(url: &String, user_agent: &String, head: bool) -> Fetch
} else {
client.get(url)
}
.header("User-Agent", user_agent.clone())
.header("User-Agent", user_agent)
.send()
.await;
match response {
Ok(r) => {
if r.status().as_u16() != 200 {
return Err(FetchError::BadStatusCode(r.status().as_u16()));
return Err(FetchError::BadStatusCode);
}
let headers = r.headers();
@@ -33,18 +30,11 @@ async fn fetch_specified(url: &String, user_agent: &String, head: bool) -> Fetch
let last_modified = headers.get("last-modified");
let date = headers.get("date");
if content_type.is_none() {
Err(FetchError::BadHeaders("Content-Type".to_string()))
} 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()))
if content_type.is_none() || etag.is_none() || last_modified.is_none() || date.is_none()
{
Err(FetchError::BadHeaders)
} else if content_type.unwrap() != "application/vnd.ms-excel" {
Err(FetchError::BadContentType(
content_type.unwrap().to_str().unwrap().to_string(),
))
Err(FetchError::BadContentType)
} else {
let etag = etag.unwrap().to_str().unwrap().to_string();
let last_modified =
@@ -59,16 +49,13 @@ async fn fetch_specified(url: &String, user_agent: &String, head: bool) -> Fetch
})
}
}
Err(error) => Err(FetchError::Unknown(Arc::new(error))),
Err(_) => Err(FetchError::Unknown),
}
}
impl BasicXlsDownloader {
pub fn new() -> Self {
BasicXlsDownloader {
url: None,
user_agent: env::var("REQWEST_USER_AGENT").expect("USER_AGENT must be set"),
}
BasicXlsDownloader { url: None }
}
}
@@ -77,12 +64,17 @@ impl XLSDownloader for BasicXlsDownloader {
if self.url.is_none() {
Err(FetchError::NoUrlProvided)
} else {
fetch_specified(self.url.as_ref().unwrap(), &self.user_agent, head).await
fetch_specified(
self.url.as_ref().unwrap(),
"t.me/polytechnic_next".to_string(),
head,
)
.await
}
}
async fn set_url(&mut self, url: String) -> FetchResult {
let result = fetch_specified(&url, &self.user_agent, true).await;
let result = fetch_specified(&url, "t.me/polytechnic_next".to_string(), true).await;
if let Ok(_) = result {
self.url = Some(url);
@@ -94,7 +86,7 @@ impl XLSDownloader for BasicXlsDownloader {
#[cfg(test)]
mod tests {
use crate::xls_downloader::basic_impl::{fetch_specified, BasicXlsDownloader};
use crate::xls_downloader::basic_impl::{BasicXlsDownloader, fetch_specified};
use crate::xls_downloader::interface::{FetchError, XLSDownloader};
#[tokio::test]
@@ -103,8 +95,8 @@ mod tests {
let user_agent = String::new();
let results = [
fetch_specified(&url, &user_agent, true).await,
fetch_specified(&url, &user_agent, false).await,
fetch_specified(&url, user_agent.clone(), true).await,
fetch_specified(&url, user_agent.clone(), false).await,
];
assert!(results[0].is_err());
@@ -117,17 +109,21 @@ mod tests {
let user_agent = String::new();
let results = [
fetch_specified(&url, &user_agent, true).await,
fetch_specified(&url, &user_agent, false).await,
fetch_specified(&url, user_agent.clone(), true).await,
fetch_specified(&url, user_agent.clone(), false).await,
];
assert!(results[0].is_err());
assert!(results[1].is_err());
let expected_error = FetchError::BadStatusCode(404);
assert_eq!(*results[0].as_ref().err().unwrap(), expected_error);
assert_eq!(*results[1].as_ref().err().unwrap(), expected_error);
assert_eq!(
*results[0].as_ref().err().unwrap(),
FetchError::BadStatusCode
);
assert_eq!(
*results[1].as_ref().err().unwrap(),
FetchError::BadStatusCode
);
}
#[tokio::test]
@@ -136,17 +132,15 @@ mod tests {
let user_agent = String::new();
let results = [
fetch_specified(&url, &user_agent, true).await,
fetch_specified(&url, &user_agent, false).await,
fetch_specified(&url, user_agent.clone(), true).await,
fetch_specified(&url, user_agent.clone(), false).await,
];
assert!(results[0].is_err());
assert!(results[1].is_err());
let expected_error = FetchError::BadHeaders("ETag".to_string());
assert_eq!(*results[0].as_ref().err().unwrap(), expected_error);
assert_eq!(*results[1].as_ref().err().unwrap(), expected_error);
assert_eq!(*results[0].as_ref().err().unwrap(), FetchError::BadHeaders);
assert_eq!(*results[1].as_ref().err().unwrap(), FetchError::BadHeaders);
}
#[tokio::test]
@@ -155,12 +149,21 @@ mod tests {
let user_agent = String::new();
let results = [
fetch_specified(&url, &user_agent, true).await,
fetch_specified(&url, &user_agent, false).await,
fetch_specified(&url, user_agent.clone(), true).await,
fetch_specified(&url, user_agent.clone(), false).await,
];
assert!(results[0].is_err());
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]
@@ -169,8 +172,8 @@ mod tests {
let user_agent = String::new();
let results = [
fetch_specified(&url, &user_agent, true).await,
fetch_specified(&url, &user_agent, false).await,
fetch_specified(&url, user_agent.clone(), true).await,
fetch_specified(&url, user_agent.clone(), false).await,
];
assert!(results[0].is_ok());

View File

@@ -1,38 +1,22 @@
use chrono::{DateTime, Utc};
use derive_more::Display;
use std::mem::discriminant;
use std::sync::Arc;
use utoipa::ToSchema;
/// XLS data retrieval errors.
#[derive(Clone, Debug, ToSchema, Display)]
#[derive(PartialEq, Debug)]
pub enum FetchError {
/// File url is not set.
#[display("The link to the timetable was not provided earlier.")]
NoUrlProvided,
/// Unknown error.
#[display("An unknown error occurred while downloading the file.")]
#[schema(value_type = String)]
Unknown(Arc<reqwest::Error>),
Unknown,
/// Server returned a status code different from 200.
#[display("Server returned a status code {_0}.")]
BadStatusCode(u16),
BadStatusCode,
/// The url leads to a file of a different type.
#[display("The link leads to a file of type '{_0}'.")]
BadContentType(String),
BadContentType,
/// Server doesn't return expected headers.
#[display("Server doesn't return expected header(s) '{_0}'.")]
BadHeaders(String),
}
impl PartialEq for FetchError {
fn eq(&self, other: &Self) -> bool {
discriminant(self) == discriminant(other)
}
BadHeaders,
}
/// Result of XLS data retrieval.