72 lines
2.2 KiB
Rust
72 lines
2.2 KiB
Rust
use anyhow::Result;
|
|
use celery::{error::TaskError, task::TaskResult};
|
|
use diesel::prelude::*;
|
|
use std::thread;
|
|
use std::time::Duration;
|
|
|
|
use crate::config;
|
|
use crate::db;
|
|
|
|
async fn fetch_schoolyears(client: &untis::Client, db_conn: &mut db::Connection) -> Result<i32> {
|
|
let existing_schoolyears = db::schema::schoolyears::table
|
|
.select(db::schema::schoolyears::untis_id)
|
|
.load::<i32>(db_conn)?;
|
|
diesel::insert_into(db::schema::schoolyears::table)
|
|
.values(
|
|
&client
|
|
.schoolyears()
|
|
.await?
|
|
.iter()
|
|
.filter(|y| !existing_schoolyears.contains(&y.id))
|
|
.map(|y| db::models::NewSchoolyear {
|
|
untis_id: y.id,
|
|
name: &y.name,
|
|
active: false,
|
|
})
|
|
.collect::<Vec<db::models::NewSchoolyear>>(),
|
|
)
|
|
.execute(db_conn)?;
|
|
|
|
let id = db::schema::schoolyears::table
|
|
.filter(db::schema::schoolyears::untis_id.eq(client.current_schoolyear().await?.id))
|
|
.select(db::schema::schoolyears::id)
|
|
.first(db_conn)?;
|
|
|
|
diesel::update(db::schema::schoolyears::table)
|
|
.set(db::schema::schoolyears::active.eq(false))
|
|
.execute(db_conn)?;
|
|
diesel::update(db::schema::schoolyears::table)
|
|
.filter(db::schema::schoolyears::id.eq(id))
|
|
.set(db::schema::schoolyears::active.eq(true))
|
|
.execute(db_conn)?;
|
|
|
|
Ok(id)
|
|
}
|
|
|
|
#[celery::task]
|
|
pub async fn update_meta() -> TaskResult<()> {
|
|
let dur = Duration::from_secs(2);
|
|
let mut client = match config::untis_from_env() {
|
|
Ok(x) => x,
|
|
Err(e) => return Err(TaskError::UnexpectedError(format!("{:?}", e))),
|
|
};
|
|
let db_conn = &mut match db::POOL.get() {
|
|
Ok(x) => x,
|
|
Err(e) => return Err(TaskError::UnexpectedError(format!("{:?}", e))),
|
|
};
|
|
thread::sleep(dur);
|
|
|
|
let schoolyear_id = match fetch_schoolyears(&client, db_conn).await {
|
|
Ok(x) => x,
|
|
Err(e) => return Err(TaskError::UnexpectedError(format!("{:?}", e))),
|
|
};
|
|
dbg!(&schoolyear_id);
|
|
thread::sleep(dur);
|
|
|
|
if let Err(e) = client.logout().await {
|
|
return Err(TaskError::UnexpectedError(format!("{:?}", e)));
|
|
}
|
|
|
|
Ok(())
|
|
}
|