126 lines
2.7 KiB
Rust
126 lines
2.7 KiB
Rust
#![feature(proc_macro_hygiene, decl_macro)]
|
|
|
|
#[macro_use]
|
|
extern crate rocket;
|
|
|
|
#[macro_use]
|
|
extern crate rocket_contrib;
|
|
|
|
#[macro_use]
|
|
extern crate anyhow;
|
|
|
|
#[macro_use]
|
|
extern crate serde;
|
|
|
|
extern crate chrono;
|
|
|
|
pub mod models;
|
|
pub mod schema;
|
|
|
|
use chrono::prelude::*;
|
|
use rocket::{
|
|
http::RawStr,
|
|
response::{NamedFile, Redirect},
|
|
State,
|
|
};
|
|
use std::{
|
|
collections::BTreeMap,
|
|
fmt::Display,
|
|
sync::{Arc, Mutex},
|
|
time::{Duration, SystemTime},
|
|
};
|
|
|
|
#[macro_use]
|
|
extern crate diesel;
|
|
extern crate dotenv;
|
|
|
|
use diesel::prelude::*;
|
|
use dotenv::dotenv;
|
|
|
|
use self::models::*;
|
|
|
|
#[database("sqlite_events")]
|
|
struct DbConn(diesel::SqliteConnection);
|
|
|
|
/*
|
|
#[get("/")]
|
|
fn index() -> Result<String, anyhow::Error> {
|
|
Ok(format!(
|
|
"Devices:\n{}\n\nwhile true; do curl https://pc.vvn.space/log/name; sleep 5; done",
|
|
"aa"
|
|
))
|
|
}
|
|
*/
|
|
|
|
#[get("/log/<device_name>/<value>")]
|
|
fn log_new(device_name: &RawStr, value: &RawStr, conn: DbConn) -> Result<String, anyhow::Error> {
|
|
let new_event = NewEvent {
|
|
devicename: device_name,
|
|
value: value.parse()?,
|
|
timestamp: &Local::now().to_rfc3339(),
|
|
};
|
|
|
|
diesel::insert_into(self::schema::events::table)
|
|
.values(&new_event)
|
|
.execute(&*conn)?;
|
|
|
|
Ok(String::from("Logged"))
|
|
}
|
|
|
|
#[get("/log/<device_name>")]
|
|
fn log_get(device_name: &RawStr, conn: DbConn) -> Result<String, anyhow::Error> {
|
|
use self::schema::events::dsl::*;
|
|
let results = events
|
|
.filter(devicename.eq(device_name.as_str()))
|
|
.load::<Event>(&*conn)?;
|
|
|
|
// convert each result into debug-print lines
|
|
let lines = results
|
|
.into_iter()
|
|
.map(|e| format!("{:?}", e))
|
|
.collect::<Vec<_>>()
|
|
.join("\n");
|
|
|
|
Ok(lines)
|
|
}
|
|
|
|
#[get("/devices")]
|
|
fn devices_get(conn: DbConn) -> Result<String, anyhow::Error> {
|
|
use self::schema::events::dsl::*;
|
|
let devices = events
|
|
.select(devicename)
|
|
.distinct()
|
|
.load::<String>(&*conn)?;
|
|
|
|
Ok(serde_json::to_string(&devices)?)
|
|
}
|
|
|
|
#[get("/device/<name>")]
|
|
fn device_get(name: &RawStr, conn: DbConn) -> Result<String, anyhow::Error> {
|
|
use self::schema::events::dsl::*;
|
|
let results = events
|
|
.filter(devicename.eq(name.as_str()))
|
|
.load::<Event>(&*conn)?;
|
|
|
|
Ok(serde_json::to_string(&results)?)
|
|
}
|
|
|
|
#[catch(404)]
|
|
fn not_found() -> Option<NamedFile> {
|
|
NamedFile::open("frontend/build/index.html").ok()
|
|
}
|
|
|
|
fn main() {
|
|
rocket::ignite()
|
|
.attach(DbConn::fairing())
|
|
.mount(
|
|
"/",
|
|
rocket_contrib::serve::StaticFiles::from("frontend/build"),
|
|
)
|
|
.mount("/api", routes![log_new, log_get, devices_get, device_get])
|
|
.register(catchers![not_found])
|
|
.launch();
|
|
|
|
println!("after");
|
|
}
|