11 Commits

Author SHA1 Message Date
fa3ea85200 temp 2026-01-14 17:31:45 -05:00
a9dc5ffdc1 Refactor to break out scheduler 2025-10-23 20:23:03 -04:00
84312d0b50 Overhaul 2025-09-19 19:33:53 -04:00
8844ee75fe Changed postgres mounts 2025-06-19 12:35:26 +00:00
995e86f229 Formatting 2025-06-03 21:57:22 -04:00
263c33fd5a Working on fixing metars, airport layout, etc 2025-06-02 17:17:09 -04:00
7dedc7a8dc Working on airport drawer 2025-05-28 21:21:25 -04:00
25608db372 Cleanup makefile 2025-05-28 19:24:18 -04:00
28dc464ec5 Fixed metar visibility and sky condition bugs 2025-05-28 19:14:10 -04:00
6ad2afe6dd Cleanup 2025-05-23 09:20:08 -04:00
ed98140d22 Metar overhaul, added footer, updated schemas 2025-05-19 20:22:44 -04:00
110 changed files with 9442 additions and 2596 deletions

15
.env
View File

@@ -38,7 +38,13 @@ SSL_CERT_KEY_PATH=../ssl/localhost.key
SMTP_USERNAME=smtp-user
SMTP_PASSWORD=smtp-password
SMTP_FROM=noreply@example.com
SMTP_SERVER=smtp.example.com
SMTP_SERVER=localhost
SMTP_PORT=1025
#SMTP_USERNAME=smtp-user
#SMTP_PASSWORD=smtp-password
#SMTP_FROM=noreply@example.com
#SMTP_SERVER=smtp.example.com
#SMTP_PORT=587
VITE_API_URL=${EXTERNAL_URL}/api
VITE_DEFAULT_LIMIT=200
@@ -46,9 +52,14 @@ __VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS=${NGINX_HOST}
ENVIRONMENT=development
ADMIN_USERNAME=admin
ADMIN_EMAIL=admin@example.com
ADMIN_PASSWORD=changeme
TEMPLATE_DIR=../templates
METAR_INTERVAL=300
AVIATION_WEATHER_URL=https://aviationweather.gov/api/data
MAILPIT_WEB_PORT=8025
MAILPIT_SMTP_PORT=1025
AVIATION_WEATHER_URL=https://aviationweather.gov

4
.gitignore vendored
View File

@@ -1,5 +1,8 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
postgres/
postgres_logs/
.vscode/
.idea/
@@ -8,7 +11,6 @@
node_modules
target/
dist/
Cargo.lock
ssl/
.DS_Store

4775
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

4
Cargo.toml Normal file
View File

@@ -0,0 +1,4 @@
[workspace]
members = [ "crates/adsb", "crates/api", "crates/lib", "crates/scheduler" ]
resolver = "2"

View File

@@ -76,24 +76,24 @@ down-backend: backend-down
run: ## Run the api
@cd api && cargo run
frontend-up: ## Start Docker containers
@docker compose --profile frontend up -d
dev-up: ## Start Docker containers
@docker compose --profile dev up -d
up-frontend: frontend-up
up-dev: dev-up
frontend-down: ## Stop Docker containers
@docker compose --profile frontend down
dev-down: ## Stop Docker containers
@docker compose --profile dev down
down-frontend: frontend-down
down-dev: dev-down
docker-prune: ## Prune the docker system
@docker system prune -a
docker-clean: ## Stop the docker containers and remove volumes
@docker compose --profile frontend --profile api --profile backend down -v
@docker compose --profile dev --profile api --profile backend down -v
docker-down: ## Stop the docker container
@docker compose --profile frontend --profile api --profile backend down
@docker compose --profile dev --profile api --profile backend down
docker-up: ## Start the docker container
@docker compose --profile backend --profile api up -d
@@ -106,7 +106,7 @@ build: version=$(if $(v),$(v),latest)
build: folder=$(if $(f),$(f),nginx)
build: registry=$(if $(r),$(r),gitea.bensherriff.com/bsherriff)
build: image=${registry}/aviation-${folder}:${version}
build: ## Build a specific docker image (`make build f=httpd`)
build: ## Build a specific docker image from a folder
docker buildx build \
-f ${folder}/Dockerfile \
-t ${image} \
@@ -121,7 +121,11 @@ push: folder=$(if $(f),$(f),nginx)
push: registry=$(if $(r),$(r),gitea.bensherriff.com/bsherriff)
push: platform=$(if $(p),$(p),linux/amd64,linux/arm64)
push: image=${registry}/aviation-${folder}:${version}
push: ## Build and push a specific docker image (`make push f=httpd`)
push: ## Build and push a specific docker image from a folder
docker buildx create \
--use \
--name default-builder \
--platform ${platform} || true; \
docker buildx build \
-f ${folder}/Dockerfile \
--platform ${platform} \

148
Taskfile.yml Normal file
View File

@@ -0,0 +1,148 @@
# https://taskfile.dev
version: '3'
dotenv: ['.env.local', '.env']
vars:
version: '{{ coalesce .version .v "latest" }}'
folder: '{{ coalesce .folder .f "nginx" }}'
registry: '{{ coalesce .registry .r "gitea.bensherriff.com/bsherriff" }}'
platform: '{{ coalesce .platform .p "linux/amd64,linux/arm64" }}'
image: '{{.registry}}/aviation-{{.folder}}:{{.version}}'
build_date:
sh: date -u +%Y-%m-%dT%H:%M:%SZ
vcs_ref:
sh: git rev-parse HEAD
context: '{{ coalesce .context .ctx "." }}'
dockerfile: >
{{- if or (eq .folder "nginx") (eq .folder "ui") -}}
{{.folder}}/Dockerfile
{{- else if eq .folder "api" -}}
crates/api/Dockerfile
{{- else if eq .folder "scheduler" -}}
crates/scheduler/Dockerfile
{{- else -}}
{{ fail (printf "Invalid folder '%s'. Valid: nginx, ui, api, scheduler" .folder) }}
{{- end -}}
tasks:
default:
cmds:
- task: docker-up
silent: true
test:
cmds:
- task: docker-backend
- task: dev-servers
dev-servers:
deps:
- task: run-api
- task: run-scheduler
- task: run-ui
# API Commands
build-api:
dir: crates/api
cmd: cargo build
format-api:
dir: crates/api
cmd: cargo fmt
run-api:
dir: crates/api
cmd: cargo run
silent: true
# Scheduler Commands
build-scheduler:
dir: crates/scheduler
cmd: cargo build
format-scheduler:
dir: crates/scheduler
cmd: cargo fmt
run-scheduler:
dir: crates/scheduler
cmd: cargo run
silent: true
# UI Commands
build-ui:
dir: ui
cmd: npm run build
format-ui:
dir: ui
cmd: npm run format
clean-ui:
dir: ui
cmd: rm -rf node_modules dist stats.html
run-ui:
dir: ui
cmd: npm run dev
silent: true
# Docker Commands
docker-backend:
cmd: docker compose --profile backend up -d
docker-up:
cmd: docker compose --profile backend --profile api up -d
docker-down:
cmd: docker compose --profile backend --profile api down
docker-clean:
cmd: docker compose --profile backend --profile api down -v
docker-refresh:
cmds:
- task: docker-clean
- task: docker-up
build:
desc: Build a specific docker image from a folder
cmds:
- |
docker buildx build \
-f {{.dockerfile}} \
-t {{.image}} \
--load \
--build-arg BUILD_DATE={{.build_date}} \
--build-arg BUILD_VERSION={{.version}} \
--build-arg VCS_REF={{.vcs_ref}} \
{{.context}}
push:
desc: Build and push a specific docker image from a folder
cmds:
- |
docker buildx create \
--use \
--driver docker-container \
--bootstrap \
--name default-builder \
--platform {{.platform}} \
|| true
ignore_error: true
- |
docker buildx build \
-f {{.dockerfile}} \
--platform {{.platform}} \
-t {{.image}} \
--push \
--build-arg BUILD_DATE={{.build_date}} \
--build-arg BUILD_VERSION={{.version}} \
--build-arg VCS_REF={{.vcs_ref}} \
{{.context}}
.
psql:
cmd: docker exec -it aviation-postgres psql -U ${POSTGRES_USER} -d ${POSTGRES_DB} -P pager=off
cert:
cmds:
- ./scripts/generate_ca_cert.sh
- ./scripts/generate_server_cert.sh ${TLS_HOST} nginx
- ./scripts/generate_server_cert.sh ${API_HOST} api
silent: true
cert-clean:
cmds:
- rm -rf ./data/certificates
silent: true

View File

@@ -1,3 +0,0 @@
indent_style = "Block"
reorder_imports = false
tab_spaces = 2

View File

@@ -1,98 +0,0 @@
mod constants;
mod device;
mod error;
mod frame;
mod hex;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use crate::device::RtlSdrDevice;
use clap::Parser;
use crate::constants::DEVICE_RTL2832U;
use crate::frame::ADSBFrame;
use crate::hex::hex_to_bytes;
#[derive(Parser, Debug)]
#[command(author, version, about = "An ADS-B Receiver")]
struct ReceiverArgs {
/// Hex-string to decode
#[arg(short = 'd', long)]
decode: Option<String>,
/// Connect to the USB device
#[arg(short = 'c', long, action)]
connect: bool,
/// Display ADS-B/Mode-S receiver info
#[arg(short = 'i', long, action)]
info: bool,
/// Enable debug logging
#[arg(short = 'D', long, action = clap::ArgAction::Count)]
debug: u8,
}
fn main() {
let args = ReceiverArgs::parse();
let default_filter = match args.debug {
0 => "warn,adsb=info", // no -D
1 => "warn,adsb=debug", // -D
_ => "trace,adsb=trace", // -DD or more
};
env_logger::init_from_env(env_logger::Env::default().filter_or("RUST_LOG", default_filter));
let device_info = DEVICE_RTL2832U;
// Handle connection
if args.connect {
log::info!("Connecting to {:?}", device_info);
let mut device = match RtlSdrDevice::open(device_info.vid, device_info.pid) {
Ok(d) => d,
Err(err) => {
log::error!("Unable to open RTL SDR device: {:?}", err);
return;
}
};
log::debug!("Connected to {:?}", device_info.to_string());
let running = Arc::new(AtomicBool::new(true));
if let Err(err) = ctrlc::set_handler({
let running = running.clone();
move || running.store(false, Ordering::SeqCst)
}) {
log::error!("Error setting Ctrl-C handler: {}", err);
running.store(false, Ordering::SeqCst);
};
if let Err(err) = device.process(running) {
log::error!("Failed to read from device: {}", err);
if let Err(err) = device.close() {
log::error!("Failed to close device: {}", err);
};
};
}
// Display dongle info
else if args.info {
RtlSdrDevice::info(device_info.vid, device_info.pid);
}
// Handle decode mode
else if let Some(mut hex_string) = args.decode {
if let Some(stripped) = hex_string.strip_prefix("0x") {
hex_string = stripped.to_string();
}
let buffer = match hex_to_bytes(&hex_string) {
Ok(buffer) => buffer,
Err(err) => {
eprintln!("Unable to convert hex to bytes: {:?}", err);
return;
}
};
if let Ok(frame) = ADSBFrame::decode(&buffer) {
println!("{:?}", frame);
};
} else {
eprintln!("No connection specified");
}
}

View File

@@ -1,38 +0,0 @@
[package]
name = "api"
version = "0.1.1"
edition = "2024"
authors = ["Ben Sherriff <ben@bensherriff.com>"]
repository = "https://gitea.bensherriff.com/bsherriff/aviation"
readme = "../README.md"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
actix-web = "4.10.2"
actix-cors = "0.7.1"
actix-multipart = "0.7.2"
chrono = { version = "0.4.41", features = ["serde"] }
dotenv = "0.15.0"
sqlx = { version = "0.8.5", features = ["runtime-tokio", "postgres", "chrono", "uuid"] }
env_logger = "0.11.8"
reqwest = "0.12.15"
serde = {version = "1.0.219", features = ["derive"]}
serde_json = "1.0.140"
tokio = { version = "1.45.0", features = ["macros", "rt", "time"] }
uuid = { version = "1.16.0", features = ["serde", "v4"] }
log = "0.4.27"
argon2 = "0.5.3"
redis = { version = "0.31.0", features = ["tokio-comp", "connection-manager", "r2d2", "json"] }
regex = "1.11.1"
futures-util = "0.3.31"
rust-s3 = "0.35.1"
rand = "0.9.1"
rand_chacha = "0.9.0"
futures = "0.3.31"
utoipa = { version = "5.3.1", features = ["chrono", "uuid", "actix_extras"] }
utoipa-swagger-ui = { version = "9.0.1", features = ["actix-web"] }
utoipa-actix-web = "0.1.2"
webpki-roots = "1.0.0"
lettre = { version = "0.11.16", features = ["builder", "smtp-transport", "tokio1-native-tls"] }
handlebars = "6.3.2"

View File

@@ -1,3 +0,0 @@
indent_style = "Block"
reorder_imports = true
tab_spaces = 2

View File

@@ -1,5 +0,0 @@
pub mod model;
pub mod routes;
pub use model::*;
pub use routes::init_routes;

View File

@@ -1,171 +0,0 @@
use crate::error::ApiResult;
use redis::{Client as RedisClient, RedisResult, aio::MultiplexedConnection as RedisConnection};
use s3::{Bucket, BucketConfiguration, Region, creds::Credentials, request::ResponseData};
use serde::{Deserialize, Serialize};
use sqlx::postgres::PgPoolOptions;
use sqlx::{Pool, Postgres};
use std::sync::OnceLock;
use std::time::Duration;
static POOL: OnceLock<Pool<Postgres>> = OnceLock::new();
static REDIS: OnceLock<RedisClient> = OnceLock::new();
static BUCKET: OnceLock<Bucket> = OnceLock::new();
pub async fn initialize() -> ApiResult<()> {
// Setup Postgres pool connection
let pool = {
let user = std::env::var("POSTGRES_USER").unwrap_or("aviation".to_string());
let password = std::env::var("POSTGRES_PASSWORD").expect("POSTGRES_PASSWORD must be set");
let host: String = std::env::var("POSTGRES_HOST").expect("POSTGRES_HOST must be set");
let port = std::env::var("POSTGRES_PORT").unwrap_or("5432".to_string());
let name = std::env::var("POSTGRES_DB").unwrap_or("aviation_db".to_string());
let db_url = format!(
"postgres://{}:{}@{}:{}/{}",
&user, &password, &host, &port, &name
);
log::info!(
"Connecting to database at postgres://{}:*****@{}:{}/{}...",
&user,
&host,
&port,
&name
);
PgPoolOptions::new()
.max_connections(5)
.acquire_timeout(Duration::from_secs(30))
.connect(&db_url)
.await?
};
match POOL.set(pool) {
Ok(_) => log::info!("Database connection established"),
Err(_) => log::warn!("Database pool already initialized"),
}
// Setup Redis connection
let redis = {
let host = std::env::var("REDIS_HOST").unwrap_or("localhost".to_string());
let port = std::env::var("REDIS_PORT").unwrap_or("6379".to_string());
let url = format!("redis://{}:{}", host, port);
log::info!("Connecting to redis at {}", &url);
RedisClient::open(url).expect("Failed to create redis client")
};
match REDIS.set(redis) {
Ok(_) => log::info!("Redis connection established"),
Err(_) => log::warn!("Redis client already initialized"),
}
// Setup Bucket connection
let bucket = {
let protocol = std::env::var("MINIO_PROTOCOL").unwrap_or("http".to_string());
let host = std::env::var("MINIO_HOST").unwrap_or("localhost".to_string());
let port = std::env::var("MINIO_PORT").unwrap_or("9000".to_string());
let user = std::env::var("MINIO_ROOT_USER").expect("MINIO_ROOT_USER is not set");
let password = std::env::var("MINIO_ROOT_PASSWORD").expect("MINIO_ROOT_PASSWORD is not set");
let bucket_name = std::env::var("MINIO_BUCKET").unwrap_or("aviation".to_string());
let url = format!("{}://{}:{}", protocol, host, port);
let region = Region::Custom {
region: "".to_string(),
endpoint: url.to_string(),
};
let credentials = Credentials {
access_key: Some(user),
secret_key: Some(password),
security_token: None,
session_token: None,
expiration: None,
};
let bucket = Bucket::new(&bucket_name, region.clone(), credentials.clone())?.with_path_style();
log::info!("Checking for object in bucket at {}", &region.endpoint());
match bucket.head_object("/").await {
Ok(_) => bucket,
Err(_) => {
log::debug!("Creating '{}' bucket", &bucket_name);
let response = match Bucket::create_with_path_style(
&bucket_name,
region,
credentials,
BucketConfiguration::default(),
)
.await
{
Ok(response) => response,
Err(err) => {
log::error!("Failed to create bucket '{}': {}", &bucket_name, err);
return Err(err.into());
}
};
response.bucket
}
}
};
match BUCKET.set(*bucket) {
Ok(_) => log::info!("Bucket connection initialized"),
Err(_) => log::warn!("Bucket connection already initialized"),
}
// Run migrations
match run_migrations().await {
Ok(_) => log::debug!("Successfully ran database migrations"),
Err(e) => log::error!("Failed to run migrations: {}", e),
}
log::info!("Database initialized");
Ok(())
}
pub fn pool() -> &'static Pool<Postgres> {
POOL.get().unwrap()
}
fn redis() -> &'static RedisClient {
REDIS.get().unwrap()
}
// pub fn redis_connection() -> RedisResult<redis::Connection> {
// let conn = redis().get_connection()?;
// Ok(conn)
// }
pub async fn redis_async_connection() -> RedisResult<RedisConnection> {
let conn = redis().get_multiplexed_async_connection().await?;
Ok(conn)
}
async fn run_migrations() -> ApiResult<()> {
log::debug!("Running database migrations");
let pool = pool();
sqlx::migrate!().run(pool).await?;
Ok(())
}
pub async fn upload_file(path: &str, content: &[u8]) -> ApiResult<ResponseData> {
let response = BUCKET.get().unwrap().put_object(path, content).await?;
Ok(response)
}
pub async fn get_file(path: &str) -> ApiResult<Vec<u8>> {
let response = BUCKET.get().unwrap().get_object(path).await?;
let bytes = response.bytes();
Ok(bytes.to_vec())
}
pub async fn delete_file(path: &str) -> ApiResult<ResponseData> {
let response = BUCKET.get().unwrap().delete_object(path).await?;
Ok(response)
}
#[derive(Serialize, Deserialize)]
pub struct Paged<T> {
pub data: T,
pub page: u32,
pub limit: u32,
pub total: i64,
}

View File

@@ -1,230 +0,0 @@
use actix_web::http::StatusCode;
use actix_web::{HttpResponse, ResponseError};
use log::warn;
use regex::Regex;
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::fmt;
pub type ApiResult<T> = Result<T, Error>;
#[derive(Debug, Deserialize, Serialize)]
pub struct Error {
pub status: u16,
pub details: String,
}
impl Error {
pub fn new(status: u16, message: String) -> Self {
Self {
status,
details: message,
}
}
pub fn to_http_response(&self) -> HttpResponse {
let status = StatusCode::from_u16(self.status).unwrap_or_else(|err| {
warn!("{}", err);
StatusCode::INTERNAL_SERVER_ERROR
});
HttpResponse::build(status).body(self.details.to_string())
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(self.details.as_str())
}
}
impl std::error::Error for Error {
fn description(&self) -> &str {
&self.details
}
}
impl ResponseError for Error {
fn error_response(&self) -> HttpResponse {
let status =
StatusCode::from_u16(self.status).unwrap_or_else(|_| StatusCode::INTERNAL_SERVER_ERROR);
let status_code = status.as_u16();
let details = match status_code {
401 => String::from("Unauthorized"),
code if code < 500 => self.details.clone(),
_ => {
log::error!("Internal server error: {}", self.details);
String::from("Internal Server Error")
}
};
HttpResponse::build(status).json(json!({ "status": status_code, "details": details }))
}
}
impl From<std::io::Error> for Error {
fn from(error: std::io::Error) -> Self {
Self::new(500, format!("Unknown IO error: {}", error))
}
}
impl From<chrono::ParseError> for Error {
fn from(error: chrono::ParseError) -> Self {
Self::new(500, format!("Parse error: {}", error))
}
}
impl From<core::num::ParseIntError> for Error {
fn from(error: core::num::ParseIntError) -> Self {
Self::new(500, format!("Parse error: {}", error))
}
}
impl From<core::num::ParseFloatError> for Error {
fn from(error: core::num::ParseFloatError) -> Self {
Self::new(500, format!("Parse error: {}", error))
}
}
impl From<std::env::VarError> for Error {
fn from(error: std::env::VarError) -> Self {
Self::new(
500,
format!("Unknown environment variable error: {}", error),
)
}
}
impl From<reqwest::Error> for Error {
fn from(error: reqwest::Error) -> Self {
match error.status() {
Some(status_code) => {
if status_code.is_client_error() {
Self::new(500, format!("Client reqwest error: {}", error))
} else if status_code.is_server_error() {
Self::new(500, format!("Server reqwest error: {}", error))
} else {
Self::new(500, format!("Unknown reqwest error: {:?}", error))
}
}
_ => Self::new(500, format!("Unknown reqwest error: {:?}", error)),
}
}
}
impl From<serde_json::Error> for Error {
fn from(error: serde_json::Error) -> Self {
Self::new(500, format!("Unknown serde_json error: {}", error))
}
}
impl From<argon2::password_hash::Error> for Error {
fn from(error: argon2::password_hash::Error) -> Self {
Self::new(500, format!("Unknown argon2 error: {}", error))
}
}
impl From<redis::RedisError> for Error {
fn from(error: redis::RedisError) -> Self {
Self::new(500, format!("Unknown redis error: {}", error))
}
}
impl From<s3::error::S3Error> for Error {
fn from(error: s3::error::S3Error) -> Self {
match error {
s3::error::S3Error::Credentials(err) => {
Self::new(500, format!("Unknown s3 credentials error: {}", err))
}
s3::error::S3Error::FromUtf8(err) => {
Self::new(500, format!("Unknown s3 from utf8 error: {}", err))
}
s3::error::S3Error::FmtError(err) => Self::new(500, format!("Unknown s3 fmt error: {}", err)),
s3::error::S3Error::HeaderToStr(err) => {
Self::new(500, format!("Unknown s3 header to str error: {}", err))
}
s3::error::S3Error::HmacInvalidLength(err) => Self::new(
500,
format!("Unknown s3 hmac invalid length error: {}", err),
),
s3::error::S3Error::Http(error) => Self::new(error.status_code().as_u16(), error.to_string()),
_ => {
let re = Regex::new(r"HTTP (\d{3})").unwrap();
// Apply the regex to the input string
if let Some(captures) = re.captures(&error.to_string()) {
if let Some(http_code_str) = captures.get(1) {
if let Ok(http_code) = http_code_str.as_str().parse::<u16>() {
return Self::new(http_code, error.to_string());
}
}
}
Self::new(500, format!("Unknown s3 error: {}", error))
}
}
}
}
impl From<sqlx::Error> for Error {
fn from(error: sqlx::Error) -> Self {
match error {
sqlx::Error::RowNotFound => Error::new(404, "Not found".to_string()),
sqlx::Error::ColumnIndexOutOfBounds { .. } => Error::new(422, error.to_string()),
sqlx::Error::ColumnNotFound { .. } => Error::new(422, error.to_string()),
sqlx::Error::ColumnDecode { .. } => Error::new(422, error.to_string()),
sqlx::Error::Decode(_) => Error::new(422, error.to_string()),
sqlx::Error::PoolTimedOut => Error::new(503, error.to_string()),
sqlx::Error::PoolClosed => Error::new(503, error.to_string()),
sqlx::Error::Tls(_) => Error::new(500, error.to_string()),
sqlx::Error::Io(_) => Error::new(500, error.to_string()),
sqlx::Error::Protocol(_) => Error::new(500, error.to_string()),
sqlx::Error::Configuration(_) => Error::new(500, error.to_string()),
sqlx::Error::AnyDriverError(_) => Error::new(500, error.to_string()),
sqlx::Error::Database(err) => {
if let Some(code) = err.code() {
match code.trim() {
// Unique violation
"23505" => return Error::new(409, err.to_string()),
_ => (),
}
}
Error::new(500, err.to_string())
}
sqlx::Error::Migrate(_) => Error::new(500, error.to_string()),
sqlx::Error::TypeNotFound { type_name } => {
Error::new(500, format!("Type not found: {}", type_name))
}
sqlx::Error::WorkerCrashed => Error::new(500, error.to_string()),
_ => Error::new(500, error.to_string()),
}
}
}
impl From<sqlx::migrate::MigrateError> for Error {
fn from(error: sqlx::migrate::MigrateError) -> Self {
Error::new(500, error.to_string())
}
}
impl From<lettre::address::AddressError> for Error {
fn from(error: lettre::address::AddressError) -> Self {
Error::new(500, error.to_string())
}
}
impl From<lettre::error::Error> for Error {
fn from(error: lettre::error::Error) -> Self {
Error::new(500, error.to_string())
}
}
impl From<lettre::transport::smtp::Error> for Error {
fn from(error: lettre::transport::smtp::Error) -> Self {
Error::new(500, error.to_string())
}
}
impl From<String> for Error {
fn from(error: String) -> Self {
Self::new(500, error)
}
}

View File

@@ -1,51 +0,0 @@
use crate::AppState;
use crate::metars::Metar;
use actix_web::{HttpRequest, HttpResponse, get, web};
use log::error;
use serde::{Deserialize, Serialize};
use utoipa::{IntoParams, ToSchema};
use utoipa_actix_web::service_config::ServiceConfig;
#[derive(Debug, Deserialize, ToSchema, IntoParams)]
#[into_params(parameter_in = Query)]
struct MetarQuery {
icaos: Option<String>,
}
#[utoipa::path(
tag = "METARs",
params(
MetarQuery,
),
responses(
(status = 200, description = "", body = [Metar]),
),
)]
#[get("/metars")]
async fn find_all(data: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
let parameters = web::Query::<MetarQuery>::from_query(req.query_string()).unwrap();
let icao_option = &parameters.icaos;
if let None = icao_option {
let empty_metars: Vec<Metar> = vec![];
return HttpResponse::Ok().json(empty_metars);
}
let icao_string = match icao_option {
Some(i) => i,
None => return HttpResponse::UnprocessableEntity().body("Missing icaos parameter"),
};
let icaos: Vec<String> = icao_string.split(',').map(|s| s.to_string()).collect();
let client = &data.client;
let metars = match Metar::find_all_distinct(client, &icaos).await {
Ok(a) => a,
Err(err) => {
error!("{}", err);
return err.to_http_response();
}
};
HttpResponse::Ok().json(metars)
}
pub fn init_routes(config: &mut ServiceConfig) {
config.service(find_all);
}

View File

@@ -1,74 +0,0 @@
// use tokio::time::{sleep, Duration};
// use crate::airports::{AirportDb, AirportFilter};
// use crate::metars::Metar;
pub fn update_airports() {
// tokio::spawn(async {
// let mut airports: Vec<AirportDb> = vec![];
// let limit = 100;
// loop {
// log::debug!("METAR update start");
// let total = match AirportDb::count(&AirportFilter::default()).await {
// Ok(t) => t,
// Err(err) => {
// log::warn!("{}", err);
// break;
// }
// };
// if total != airports.len() as i64 {
// log::debug!("{} cached airports, expected {}", airports.len(), total);
// airports = vec![];
// let pages = ((total as f32) / (if limit <= 0 { 1 } else { limit } as f32)).ceil() as i32;
// for page in 1..(pages + 1) {
// match AirportDb::find_all(&AirportFilter::default(), limit, page).await {
// Ok(mut a) => airports.append(&mut a),
// Err(err) => {
// log::warn!("{}", err);
// break;
// }
// }
// }
// }
// log::debug!("Updating {} airport METARS", airports.len());
//
// let airport_icaos: Vec<String> = airports.iter().map(|a| a.icao.to_string()).collect();
// let mut peekable = airport_icaos.into_iter().peekable();
// let mut observation_time = chrono::Utc::now().timestamp();
//
// if peekable.peek().is_none() {
// log::debug!("No airports to update, sleeping for 1 hour");
// sleep(Duration::from_secs(3600)).await;
// continue;
// }
//
// while peekable.peek().is_some() {
// let chunk: Vec<String> = peekable.by_ref().take(limit as usize).collect();
// let icao_string = chunk.join(",");
// log::warn!("Updating METARS for: {}", &icao_string); // TODO: back to trace after
// match Metar::find_all(&[&icao_string]).await {
// Ok(metars) => {
// // Find the oldest observation time
// for metar in metars {
// if metar.observation_time.timestamp() < observation_time {
// observation_time = metar.observation_time.timestamp();
// }
// }
// }
// Err(err) => {
// log::warn!("{}", err);
// }
// }
// // Sleep for 100ms between chunks to avoid rate limiting
// sleep(Duration::from_millis(100)).await;
// }
// log::debug!("METAR update complete");
// // Sleep until the earliest observation time is 1 hour old
// // Bounded by 1 and 3600 seconds
// let now = chrono::Utc::now().timestamp();
// let sleep_time = std::cmp::min(std::cmp::max(1, now - (observation_time + 3600)), 3600);
// log::debug!("Next update in {} seconds", sleep_time);
// sleep(Duration::from_secs(sleep_time as u64)).await;
// }
// });
}

View File

@@ -1,5 +0,0 @@
mod model;
mod routes;
pub use model::*;
pub use routes::init_routes;

View File

@@ -1,167 +0,0 @@
// use actix_multipart::Multipart;
// use actix_web::{get, post, delete, web, HttpResponse, ResponseError};
// use futures_util::StreamExt;
// use crate::{
// auth::Auth,
// db::{delete_file, get_file, upload_file},
// error::ServiceError,
// users::User,
// };
// #[get("/favorites")]
// async fn get_favorites(auth: Auth) -> HttpResponse {
// match User::get_by_email(&auth.user.email) {
// Ok(user) => return HttpResponse::Ok().json(user.favorites),
// Err(err) => return ResponseError::error_response(&err),
// }
// }
// #[post("/favorites/{icao}")]
// async fn add_favorite(icao: web::Path<String>, auth: Auth) -> HttpResponse {
// match User::get_by_email(&auth.user.email) {
// Ok(user) => {
// if user.favorites.contains(&icao) {
// // Check if the airport ICAO is already in the user's favorites
// return HttpResponse::Conflict().finish();
// } else {
// // Add the airport ICAO to the user's favorites
// let mut favorites = user.favorites;
// favorites.push(icao.into_inner());
// match User::update_favorites(&user.email, favorites) {
// Ok(_) => return HttpResponse::Ok().finish(),
// Err(err) => return ResponseError::error_response(&err),
// }
// }
// }
// Err(err) => return ResponseError::error_response(&err),
// }
// }
// #[delete("/favorites/{icao}")]
// async fn delete_favorite(icao: web::Path<String>, auth: Auth) -> HttpResponse {
// let icao: String = icao.into_inner();
// match User::get_by_email(&auth.user.email) {
// Ok(user) => {
// if user.favorites.contains(&icao) {
// // Check if the airport ICAO is already in the user's favorites
// let mut favorites = user.favorites;
// favorites.retain(|x| x != &icao);
// match User::update_favorites(&user.email, favorites) {
// Ok(_) => return HttpResponse::Ok().finish(),
// Err(err) => return ResponseError::error_response(&err),
// }
// } else {
// // Remove the airport ICAO from the user's favorites
// return HttpResponse::Conflict().finish();
// }
// }
// Err(err) => return ResponseError::error_response(&err),
// }
// }
// #[post("/picture")]
// async fn set_picture(mut payload: Multipart, auth: Auth) -> HttpResponse {
// while let Some(item) = payload.next().await {
// let mut bytes = web::BytesMut::new();
// let mut field = match item {
// Ok(field) => field,
// Err(err) => return ResponseError::error_response(&err),
// };
// let content_type = field.content_disposition();
// let filename = match content_type.unwrap().get_filename() {
// Some(name) => match name.split(".").last() {
// Some(ext) => match ext {
// "apng" | "avif" | "gif" | "jpg" | "jpeg" | "jfif" | "pjpeg" | "pjp" | "png" | "svg"
// | "webp" => name,
// _ => {
// return ResponseError::error_response(&ServiceError::new(
// 400,
// "File extension is not supported".to_string(),
// ))
// }
// },
// None => {
// return ResponseError::error_response(&ServiceError::new(
// 400,
// "Unknown file extension".to_string(),
// ))
// }
// },
// None => {
// return ResponseError::error_response(&ServiceError::new(
// 400,
// "File name is not provided".to_string(),
// ))
// }
// };
// let path = format!("users/{}/{}", auth.user.email, filename);
// while let Some(chunk) = field.next().await {
// let data = match chunk {
// Ok(data) => data,
// Err(err) => return ResponseError::error_response(&err),
// };
// bytes.extend_from_slice(&data);
// }
// match upload_file(&path, &bytes).await {
// Ok(_) => {
// match User::update_profile_picture(&auth.user.email, Some(&path)) {
// Ok(_) => {}
// Err(err) => return ResponseError::error_response(&err),
// };
// }
// Err(err) => return ResponseError::error_response(&err),
// };
// }
// HttpResponse::Ok().finish()
// }
// #[get("/picture")]
// async fn get_picture(auth: Auth) -> HttpResponse {
// let user = match User::get_by_email(&auth.user.email) {
// Ok(user) => user,
// Err(err) => return ResponseError::error_response(&err),
// };
// if let Some(path) = user.profile_picture {
// match get_file(&path).await {
// Ok(bytes) => HttpResponse::Ok().body(bytes),
// Err(err) => ResponseError::error_response(&err),
// }
// } else {
// HttpResponse::NotFound().finish()
// }
// }
// #[delete("/picture")]
// async fn delete_picture(auth: Auth) -> HttpResponse {
// let user = match User::get_by_email(&auth.user.email) {
// Ok(user) => user,
// Err(err) => return ResponseError::error_response(&err),
// };
// if let Some(path) = user.profile_picture {
// match delete_file(&path).await {
// Ok(_) => match User::update_profile_picture(&auth.user.email, None) {
// Ok(_) => HttpResponse::Ok().finish(),
// Err(err) => ResponseError::error_response(&err),
// },
// Err(err) => ResponseError::error_response(&err),
// }
// } else {
// HttpResponse::NotFound().finish()
// }
// }
use utoipa_actix_web::service_config::ServiceConfig;
pub fn init_routes(_config: &mut ServiceConfig) {
// config.service(
// web::scope("users")
// .service(get_favorites)
// .service(add_favorite)
// .service(delete_favorite)
// .service(set_picture)
// .service(get_picture)
// .service(delete_picture),
// );
}

View File

@@ -1,7 +1,7 @@
meta {
name: Change Password
type: http
seq: 4
seq: 7
}
put {
@@ -11,7 +11,9 @@ put {
}
body:json {
"New Password"
{
"password": "New Password"
}
}
script:post-response {

View File

@@ -0,0 +1,18 @@
meta {
name: Confirm Password Reset
type: http
seq: 9
}
post {
url: {{API_URL}}/account/password/verify
body: json
auth: none
}
body:json {
{
"token": "token",
"password": "New Password"
}
}

View File

@@ -1,7 +1,7 @@
meta {
name: Get Profile
type: http
seq: 7
seq: 11
}
get {

View File

@@ -0,0 +1,18 @@
meta {
name: Login Admin (Default)
type: http
seq: 5
}
post {
url: {{API_URL}}/account/login
body: json
auth: none
}
body:json {
{
"username": "admin",
"password": "changeme"
}
}

View File

@@ -1,7 +1,7 @@
meta {
name: Login
type: http
seq: 2
seq: 4
}
post {
@@ -12,7 +12,7 @@ post {
body:json {
{
"email": "admin@example.com",
"username": "user",
"password": "changeme"
}
}

View File

@@ -1,7 +1,7 @@
meta {
name: Logout
type: http
seq: 3
seq: 6
}
post {
@@ -12,7 +12,7 @@ post {
body:json {
{
"email": "john.doe@gmail.com",
"password": "fake_password123"
"email": "user@gmail.com",
"password": "changeme"
}
}

View File

@@ -1,7 +1,7 @@
meta {
name: Refresh Session
type: http
seq: 6
seq: 10
}
get {

View File

@@ -12,9 +12,10 @@ post {
body:json {
{
"email": "john.doe@gmail.com",
"password": "fake_password123",
"first_name": "John",
"last_name": "Doe"
"username": "user",
"email": "user@example.com",
"password": "changeme",
"firstName": "John",
"lastName": "Doe"
}
}

View File

@@ -0,0 +1,11 @@
meta {
name: Resend Email Confirmation
type: http
seq: 2
}
post {
url: {{API_URL}}/account/register/resend
body: none
auth: none
}

View File

@@ -1,11 +1,17 @@
meta {
name: Reset Password
type: http
seq: 5
seq: 8
}
post {
url: {{API_URL}}/account/password/reset
body: none
body: json
auth: none
}
body:json {
{
"email": "user@example.com"
}
}

View File

@@ -0,0 +1,17 @@
meta {
name: Verify Email Confirmation
type: http
seq: 3
}
post {
url: {{API_URL}}/account/register/verify
body: json
auth: none
}
body:json {
{
"token": "token"
}
}

3
bruno/Account/folder.bru Normal file
View File

@@ -0,0 +1,3 @@
meta {
name: Account
}

475
crates/adsb/Cargo.lock generated Normal file
View File

@@ -0,0 +1,475 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "adsb"
version = "0.1.0"
dependencies = [
"clap",
"ctrlc",
"env_logger",
"log",
"rusb",
]
[[package]]
name = "aho-corasick"
version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916"
dependencies = [
"memchr",
]
[[package]]
name = "anstream"
version = "0.6.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8acc5369981196006228e28809f761875c0327210a891e941f4c683b3a99529b"
dependencies = [
"anstyle",
"anstyle-parse",
"anstyle-query",
"anstyle-wincon",
"colorchoice",
"is_terminal_polyfill",
"utf8parse",
]
[[package]]
name = "anstyle"
version = "1.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "55cc3b69f167a1ef2e161439aa98aed94e6028e5f9a59be9a6ffb47aef1651f9"
[[package]]
name = "anstyle-parse"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b2d16507662817a6a20a9ea92df6652ee4f94f914589377d69f3b21bc5798a9"
dependencies = [
"utf8parse",
]
[[package]]
name = "anstyle-query"
version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "79947af37f4177cfead1110013d678905c37501914fba0efea834c3fe9a8d60c"
dependencies = [
"windows-sys",
]
[[package]]
name = "anstyle-wincon"
version = "3.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca3534e77181a9cc07539ad51f2141fe32f6c3ffd4df76db8ad92346b003ae4e"
dependencies = [
"anstyle",
"once_cell",
"windows-sys",
]
[[package]]
name = "bitflags"
version = "2.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c8214115b7bf84099f1309324e63141d4c5d7cc26862f97a0a857dbefe165bd"
[[package]]
name = "cc"
version = "1.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e3a13707ac958681c13b39b458c073d0d9bc8a22cb1b2f4c8e55eb72c13f362"
dependencies = [
"shlex",
]
[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "cfg_aliases"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
[[package]]
name = "clap"
version = "4.5.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eccb054f56cbd38340b380d4a8e69ef1f02f1af43db2f0cc817a4774d80ae071"
dependencies = [
"clap_builder",
"clap_derive",
]
[[package]]
name = "clap_builder"
version = "4.5.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "efd9466fac8543255d3b1fcad4762c5e116ffe808c8a3043d4263cd4fd4862a2"
dependencies = [
"anstream",
"anstyle",
"clap_lex",
"strsim",
]
[[package]]
name = "clap_derive"
version = "4.5.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09176aae279615badda0765c0c0b3f6ed53f4709118af73cf4655d85d1530cd7"
dependencies = [
"heck",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "clap_lex"
version = "0.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f46ad14479a25103f283c0f10005961cf086d8dc42205bb44c46ac563475dca6"
[[package]]
name = "colorchoice"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b63caa9aa9397e2d9480a9b13673856c78d8ac123288526c37d7839f2a86990"
[[package]]
name = "ctrlc"
version = "3.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "697b5419f348fd5ae2478e8018cb016c00a5881c7f46c717de98ffd135a5651c"
dependencies = [
"nix",
"windows-sys",
]
[[package]]
name = "env_filter"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "186e05a59d4c50738528153b83b0b0194d3a29507dfec16eccd4b342903397d0"
dependencies = [
"log",
"regex",
]
[[package]]
name = "env_logger"
version = "0.11.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c863f0904021b108aa8b2f55046443e6b1ebde8fd4a15c399893aae4fa069f"
dependencies = [
"anstream",
"anstyle",
"env_filter",
"jiff",
"log",
]
[[package]]
name = "heck"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "is_terminal_polyfill"
version = "1.70.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7943c866cc5cd64cbc25b2e01621d07fa8eb2a1a23160ee81ce38704e97b8ecf"
[[package]]
name = "jiff"
version = "0.2.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a064218214dc6a10fbae5ec5fa888d80c45d611aba169222fc272072bf7aef6"
dependencies = [
"jiff-static",
"log",
"portable-atomic",
"portable-atomic-util",
"serde",
]
[[package]]
name = "jiff-static"
version = "0.2.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "199b7932d97e325aff3a7030e141eafe7f2c6268e1d1b24859b753a627f45254"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "libc"
version = "0.2.172"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d750af042f7ef4f724306de029d18836c26c1765a54a6a3f094cbd23a7267ffa"
[[package]]
name = "libusb1-sys"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da050ade7ac4ff1ba5379af847a10a10a8e284181e060105bf8d86960ce9ce0f"
dependencies = [
"cc",
"libc",
"pkg-config",
"vcpkg",
]
[[package]]
name = "log"
version = "0.4.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13dc2df351e3202783a1fe0d44375f7295ffb4049267b0f3018346dc122a1d94"
[[package]]
name = "memchr"
version = "2.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3"
[[package]]
name = "nix"
version = "0.29.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46"
dependencies = [
"bitflags",
"cfg-if",
"cfg_aliases",
"libc",
]
[[package]]
name = "once_cell"
version = "1.21.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
[[package]]
name = "pkg-config"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c"
[[package]]
name = "portable-atomic"
version = "1.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "350e9b48cbc6b0e028b0473b114454c6316e57336ee184ceab6e53f72c178b3e"
[[package]]
name = "portable-atomic-util"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8a2f0d8d040d7848a709caf78912debcc3f33ee4b3cac47d73d1e1069e83507"
dependencies = [
"portable-atomic",
]
[[package]]
name = "proc-macro2"
version = "1.0.95"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02b3e5e68a3a1a02aad3ec490a98007cbc13c37cbe84a3cd7b8e406d76e7f778"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d"
dependencies = [
"proc-macro2",
]
[[package]]
name = "regex"
version = "1.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c"
[[package]]
name = "rusb"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ab9f9ff05b63a786553a4c02943b74b34a988448671001e9a27e2f0565cc05a4"
dependencies = [
"libc",
"libusb1-sys",
]
[[package]]
name = "serde"
version = "1.0.219"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5f0e2c6ed6606019b4e29e69dbaba95b11854410e5347d525002456dbbb786b6"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.219"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b0276cf7f2c73365f7157c8123c21cd9a50fbbd844757af28ca1f5925fc2a00"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "shlex"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
[[package]]
name = "strsim"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "syn"
version = "2.0.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b09a44accad81e1ba1cd74a32461ba89dee89095ba17b32f5d03683b1b1fc2a0"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "unicode-ident"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512"
[[package]]
name = "utf8parse"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]]
name = "vcpkg"
version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
[[package]]
name = "windows-sys"
version = "0.59.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
dependencies = [
"windows-targets",
]
[[package]]
name = "windows-targets"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
dependencies = [
"windows_aarch64_gnullvm",
"windows_aarch64_msvc",
"windows_i686_gnu",
"windows_i686_gnullvm",
"windows_i686_msvc",
"windows_x86_64_gnu",
"windows_x86_64_gnullvm",
"windows_x86_64_msvc",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
[[package]]
name = "windows_aarch64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
[[package]]
name = "windows_i686_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
[[package]]
name = "windows_i686_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
[[package]]
name = "windows_i686_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
[[package]]
name = "windows_x86_64_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
[[package]]
name = "windows_x86_64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"

View File

@@ -1,3 +1,3 @@
[toolchain]
channel = "stable"
channel = "nightly"
components = ["rustfmt", "clippy"]

231
crates/adsb/src/main.rs Normal file
View File

@@ -0,0 +1,231 @@
#![feature(extern_types)]
mod constants;
mod device;
mod error;
mod frame;
mod hex;
use std::ffi::{c_char, c_int, c_void, CStr};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use crate::device::RtlSdrDevice;
use clap::Parser;
use crate::constants::DEVICE_RTL2832U;
use crate::frame::ADSBFrame;
use crate::hex::hex_to_bytes;
#[link(name = "rtlsdr")]
unsafe extern "C" {
fn rtlsdr_get_device_count() -> u32;
fn rtlsdr_get_device_name(index: u32) -> *const c_char;
fn rtlsdr_get_device_usb_strings(
index: u32,
manufact: *mut c_char,
product: *mut c_char,
serial: *mut c_char,
) -> c_int;
type rtlsdr_dev_t;
fn rtlsdr_open(dev: *mut *mut rtlsdr_dev_t, index: u32) -> c_int;
fn rtlsdr_close(dev: *mut rtlsdr_dev_t) -> c_int;
fn rtlsdr_set_sample_rate(dev: *mut rtlsdr_dev_t, rate: u32) -> c_int;
fn rtlsdr_set_center_freq(dev: *mut rtlsdr_dev_t, freq: u32) -> c_int;
fn rtlsdr_set_agc_mode(dev: *mut rtlsdr_dev_t, on: c_int) -> c_int;
fn rtlsdr_set_tuner_gain_mode(dev: *mut rtlsdr_dev_t, manual: c_int) -> c_int;
fn rtlsdr_reset_buffer(dev: *mut rtlsdr_dev_t) -> c_int;
fn rtlsdr_read_sync(
dev: *mut rtlsdr_dev_t,
buf: *mut c_void,
len: c_int,
n_read: *mut c_int,
) -> c_int;
}
struct Device {
ptr: *mut rtlsdr_dev_t,
}
impl Device {
fn open(index: u32) -> Result<Self, String> {
let mut dev: *mut rtlsdr_dev_t = std::ptr::null_mut();
let rc = unsafe { rtlsdr_open(&mut dev as *mut _, index) };
if rc != 0 {
return Err(format!("Failed to open device: {}", rc));
}
Ok(Self { ptr: dev })
}
fn set_sample_rate(&mut self, rate: u32) -> Result<(), String> {
let rc = unsafe { rtlsdr_set_sample_rate(self.ptr, rate) };
if rc != 0 {
return Err(format!("Failed to set sample rate: {}", rc));
}
Ok(())
}
fn set_center_freq(&mut self, freq: u32) -> Result<(), String> {
let rc = unsafe { rtlsdr_set_center_freq(self.ptr, freq) };
if rc != 0 {
return Err(format!("Failed to set center freq: {}", rc));
}
Ok(())
}
fn set_agc(&mut self, on: bool) -> Result<(), String> {
let rc = unsafe { rtlsdr_set_agc_mode(self.ptr, if on { 1 } else { 0 }) };
if rc != 0 {
return Err(format!("Failed to set AGC: {}", rc));
}
Ok(())
}
// manual = false -> auto-gain, manual = true -> set a gain
fn set_tuner_gain_mode(&mut self, manual: bool) -> Result<(), String> {
let rc = unsafe { rtlsdr_set_tuner_gain_mode(self.ptr, if manual { 1 } else { 0 }) };
if rc != 0 {
return Err(format!("Failed to set tuner gain mode: {}", rc));
}
Ok(())
}
fn set_buffer(&mut self) -> Result<(), String> {
let rc = unsafe { rtlsdr_reset_buffer(self.ptr) };
if rc != 0 {
return Err(format!("Failed to reset buffer: {}", rc));
}
Ok(())
}
// Returns the number of bytes placed in buf (I/Q interleaved, u8
fn read_sync(&mut self, buf: &mut [u8]) -> Result<usize, String> {
let mut n_read: c_int = 0;
let rc = unsafe {
rtlsdr_read_sync(
self.ptr,
buf.as_mut_ptr() as *mut c_void,
buf.len() as c_int,
&mut n_read as *mut _,
)
};
if rc != 0 {
return Err(format!("Failed to read sync: {}", rc));
}
Ok(n_read as usize)
}
}
impl Drop for Device {
fn drop(&mut self) {
if !self.ptr.is_null() {
unsafe { rtlsdr_close(self.ptr) };
self.ptr = std::ptr::null_mut();
}
}
}
fn cstr_from_ptr(ptr: *const c_char) -> String {
if ptr.is_null() {
return String::new();
}
unsafe { CStr::from_ptr(ptr).to_string_lossy().into_owned() }
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
unsafe {
let count = rtlsdr_get_device_count();
log::debug!("Found {} devices", count);
for i in 0..count {
let name = cstr_from_ptr(rtlsdr_get_device_name(i));
log::debug!("Device {}: {}", i, name);
}
}
Ok(())
}
// #[derive(Parser, Debug)]
// #[command(author, version, about = "An ADS-B Receiver")]
// struct ReceiverArgs {
// /// Hex-string to decode
// #[arg(short = 'd', long)]
// decode: Option<String>,
//
// /// Connect to the USB device
// #[arg(short = 'c', long, action)]
// connect: bool,
//
// /// Display ADS-B/Mode-S receiver info
// #[arg(short = 'i', long, action)]
// info: bool,
//
// /// Enable debug logging
// #[arg(short = 'D', long, action = clap::ArgAction::Count)]
// debug: u8,
// }
//
// fn main() {
// let args = ReceiverArgs::parse();
//
// let default_filter = match args.debug {
// 0 => "warn,adsb=info", // no -D
// 1 => "warn,adsb=debug", // -D
// _ => "trace,adsb=trace", // -DD or more
// };
//
// env_logger::init_from_env(env_logger::Env::default().filter_or("RUST_LOG", default_filter));
//
// let device_info = DEVICE_RTL2832U;
//
// // Handle connection
// if args.connect {
// log::info!("Connecting to {:?}", device_info);
// let mut device = match RtlSdrDevice::open(device_info.vid, device_info.pid) {
// Ok(d) => d,
// Err(err) => {
// log::error!("Unable to open RTL SDR device: {:?}", err);
// return;
// }
// };
// log::debug!("Connected to {:?}", device_info.to_string());
//
// let running = Arc::new(AtomicBool::new(true));
// if let Err(err) = ctrlc::set_handler({
// let running = running.clone();
// move || running.store(false, Ordering::SeqCst)
// }) {
// log::error!("Error setting Ctrl-C handler: {}", err);
// running.store(false, Ordering::SeqCst);
// };
//
// if let Err(err) = device.process(running) {
// log::error!("Failed to read from device: {}", err);
// if let Err(err) = device.close() {
// log::error!("Failed to close device: {}", err);
// };
// };
// }
// // Display dongle info
// else if args.info {
// RtlSdrDevice::info(device_info.vid, device_info.pid);
// }
// // Handle decode mode
// else if let Some(mut hex_string) = args.decode {
// if let Some(stripped) = hex_string.strip_prefix("0x") {
// hex_string = stripped.to_string();
// }
// let buffer = match hex_to_bytes(&hex_string) {
// Ok(buffer) => buffer,
// Err(err) => {
// eprintln!("Unable to convert hex to bytes: {:?}", err);
// return;
// }
// };
// if let Ok(frame) = ADSBFrame::decode(&buffer) {
// println!("{:?}", frame);
// };
// } else {
// eprintln!("No connection specified");
// }
// }

File diff suppressed because it is too large Load Diff

29
crates/api/Cargo.toml Normal file
View File

@@ -0,0 +1,29 @@
[package]
name = "api"
version = "0.1.3"
edition = "2024"
authors = ["Ben Sherriff <ben@bensherriff.com>"]
repository = "https://gitea.bensherriff.com/bsherriff/aviation"
readme = "../../README.md"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
lib = { path = "../lib" }
actix-web = "4.11.0"
actix-cors = "0.7.1"
actix-multipart = "0.7.2"
chrono = { version = "0.4.42", features = ["serde"] }
dotenv = "0.15.0"
env_logger = "0.11.8"
serde = {version = "1.0.219", features = ["derive"]}
serde_json = "1.0.142"
tokio = { version = "1.47.1", features = ["macros", "rt", "time"] }
log = "0.4.28"
argon2 = "0.5.3"
futures-util = "0.3.31"
utoipa = { version = "5.4.0", features = ["chrono", "uuid", "actix_extras"] }
utoipa-swagger-ui = { version = "9.0.2", features = ["actix-web"] }
utoipa-actix-web = "0.1.2"
lettre = { version = "0.11.18", features = ["builder", "smtp-transport", "tokio1-native-tls"] }
handlebars = "6.3.2"

View File

@@ -4,9 +4,9 @@
FROM rust:bookworm AS builder
WORKDIR /builder
COPY api/migrations ./migrations
COPY api/src ./src
COPY api/Cargo.toml ./
COPY crates/lib /lib
COPY crates/api/src ./src
COPY crates/api/Cargo.toml ./
RUN apt-get update && apt-get install -y cmake
RUN cargo build --release

View File

@@ -1,10 +1,12 @@
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use super::{SESSION_COOKIE_NAME, Session};
use crate::{error::Error, users::User};
use actix_web::{Error as ActixError, FromRequest, HttpRequest, dev::Payload, http};
use crate::error::{ApiResult, Error};
use actix_web::{Error as ActixError, FromRequest, HttpRequest, dev::Payload, http, web};
use serde::{Deserialize, Serialize};
use lib::accounts::User;
use lib::state::AppState;
#[derive(Debug, Serialize, Deserialize)]
pub struct Auth {
@@ -18,29 +20,37 @@ impl FromRequest for Auth {
type Future = Pin<Box<dyn Future<Output = Result<Self, Self::Error>>>>;
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
// Check for API key
let state = match req.app_data::<web::Data<AppState>>() {
Some(state) => state,
None => return Box::pin(
async { Err(Error::new(500, "Internal server error".to_string()).into()) },
)
};
// Check for an API key
match req
.headers()
.get(http::header::AUTHORIZATION)
.map(|h| h.to_str().unwrap().split_at(7).1.to_string())
{
Some(key_id) => {
let state = Arc::clone(&state);
let fut = async move {
// Check if the Session API key exists
let api_key = match Session::get(&key_id).await {
let api_key = match Session::get(&state, &key_id).await {
Ok(session) => session,
Err(err) => {
log::error!("Invalid session auth attempt: {}", err);
return Err(Error::new(401, "API Key does not exist".to_string()).into());
}
};
match User::select(&api_key.user_id).await {
match User::select(&state.pool, &api_key.username).await {
Some(user) => Ok(Auth {
session_id: None,
api_key: Some(key_id),
user,
}),
None => Err(Error::new(404, format!("User {} not found", api_key.user_id)).into()),
None => Err(Error::new(404, format!("User {} not found", api_key.username)).into()),
}
};
return Box::pin(fut);
@@ -77,15 +87,16 @@ impl FromRequest for Auth {
let ip_address = req.peer_addr().unwrap().ip().to_string();
// Verify the session
let state = Arc::clone(&state); // state: Arc<State>
let fut = async move {
match Session::verify(&session_id, &ip_address).await {
Ok(session) => match User::select(&session.user_id).await {
match Session::verify(&state, &session_id, &ip_address).await {
Ok(session) => match User::select(&state.pool, &session.username).await {
Some(user) => Ok(Auth {
session_id: Some(session_id),
api_key: None,
user,
}),
None => Err(Error::new(404, format!("User {} not found", session.user_id)).into()),
None => Err(Error::new(404, format!("User {} not found", session.username)).into()),
},
Err(err) => Err(err.into()),
}
@@ -93,3 +104,16 @@ impl FromRequest for Auth {
Box::pin(fut)
}
}
impl Auth {
pub fn verify_role(&self, role: &str) -> ApiResult<()> {
if self.user.role == role {
Ok(())
} else {
Err(Error {
status: 403,
details: "User does not have permission to perform this action.".to_string(),
})
}
}
}

View File

@@ -1,12 +1,11 @@
use crate::account::hash;
use crate::db::redis_async_connection;
use lib::accounts::{csprng, hash};
use crate::error::{ApiResult, Error};
use crate::smtp;
use chrono::{Datelike, Utc};
use redis::{AsyncCommands, RedisResult};
use serde::{Deserialize, Serialize};
use std::path::Path;
use std::{env, fs};
use lib::state::AppState;
#[derive(Debug, Serialize, Deserialize)]
pub struct EmailToken {
@@ -24,37 +23,28 @@ impl EmailToken {
}
}
pub async fn store(&self, ttl_secs: i64) -> ApiResult<()> {
let mut conn = redis_async_connection().await?;
pub async fn store(&self, state: &AppState, ttl_secs: i64) -> ApiResult<()> {
let key = self.token.clone();
let value = serde_json::to_string(self)?;
let now = Utc::now();
let expires_at = now + chrono::Duration::seconds(ttl_secs);
let ttl = expires_at.timestamp() - now.timestamp();
let result: RedisResult<()> = conn.set_ex(key, &value, ttl as u64).await;
let _ = state.set_ex(&key, &value, ttl as u64).await?;
Ok(())
}
pub async fn get(state: &AppState, token: &str) -> ApiResult<Self> {
let result: Option<String> = state.get(token).await?;
match result {
Ok(_) => Ok(()),
Err(err) => Err(err.into()),
Some(value) => Ok(serde_json::from_str(&value)?),
None => Err(Error::new(404, format!("Missing email token {}", token))),
}
}
pub async fn get(token: &str) -> ApiResult<Self> {
let mut conn = redis_async_connection().await?;
let result: RedisResult<Option<String>> = conn.get(token).await;
match result {
Ok(Some(value)) => Ok(serde_json::from_str(&value)?),
Ok(None) => Err(Error::new(404, format!("Missing email token {}", token))),
Err(err) => Err(err.into()),
}
}
pub async fn delete(token: &str) -> ApiResult<()> {
let mut conn = redis_async_connection().await?;
let result: RedisResult<()> = conn.del(token).await;
match result {
Ok(_) => Ok(()),
Err(err) => Err(err.into()),
}
pub async fn delete(state: &AppState, token: &str) -> ApiResult<()> {
let _ = state.del(token).await;
Ok(())
}
}
@@ -66,7 +56,7 @@ pub struct SimpleEmailCtx {
pub year: i32,
}
pub fn send_password_reset_email(
pub async fn send_password_reset_email(
email: &str,
email_token: &EmailToken,
ip_address: &str,
@@ -99,7 +89,7 @@ pub fn send_password_reset_email(
.render_template(&template_html, &ctx)
.unwrap();
match smtp::send_email(&email, subject, plain, html) {
match smtp::send_email(&email, subject, plain, html).await {
Ok(_) => Ok(()),
Err(err) => {
log::error!(
@@ -113,11 +103,11 @@ pub fn send_password_reset_email(
}
}
pub fn send_confirm_email(
email: &str,
email_token: &EmailToken,
ip_address: &str,
) -> ApiResult<()> {
pub async fn send_confirm_email(state: &AppState, email: &str, ip_address: &str) -> ApiResult<()> {
let token = csprng(128);
let email_token = EmailToken::new(email.to_string(), token, &ip_address);
email_token.store(state, 86400).await?;
let base_url = env::var("EXTERNAL_URL")?;
let link = format!("{base_url}/profile/confirm?token={}", email_token.token);
let subject = "Confirm your email address";
@@ -146,16 +136,16 @@ pub fn send_confirm_email(
.render_template(&template_html, &ctx)
.unwrap();
match smtp::send_email(&email, subject, plain, html) {
Ok(_) => Ok(()),
Err(err) => {
if let Err(err) = smtp::send_email(&email, subject, plain, html).await {
log::error!(
"Invalid email confirmation attempt [Email: {}] [IP Address: {}]: {}",
email,
ip_address,
err
);
Err(err.into())
}
let _ = EmailToken::delete(state, &email_token.token);
return Err(err);
}
Ok(())
}

View File

@@ -0,0 +1,7 @@
mod auth;
mod email_token;
mod session;
pub use auth::*;
pub use email_token::*;
pub use session::*;

View File

@@ -1,14 +1,10 @@
use super::{csprng, hash, verify_hash};
use crate::{
db::redis_async_connection,
error::{ApiResult, Error},
};
use lib::accounts::{csprng, hash, verify_hash};
use crate::error::{ApiResult, Error};
use actix_web::cookie::{Cookie, time::Duration};
use chrono::{DateTime, Utc};
use redis::{AsyncCommands, RedisResult};
use serde::{Deserialize, Serialize};
use tokio::task;
use uuid::Uuid;
use lib::error::CoreResult;
use lib::state::AppState;
const DEFAULT_SESSION_TTL: i64 = 86400; // (In seconds) 24 hours
pub const SESSION_COOKIE_NAME: &str = "session";
@@ -17,22 +13,22 @@ pub const SESSION_EXPIRATION_COOKIE_NAME: &str = "session_expiration";
#[derive(Debug, Serialize, Deserialize)]
pub struct Session {
pub session_id: String,
pub user_id: Uuid,
pub username: String,
pub ip_address: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub expires_at: Option<DateTime<Utc>>,
}
impl Session {
pub fn default(user_id: &Uuid, ip_address: &str) -> Self {
Self::new(64, user_id, ip_address, Some(DEFAULT_SESSION_TTL))
pub fn default(username: &str, ip_address: &str) -> Self {
Self::new(64, username, ip_address, Some(DEFAULT_SESSION_TTL))
}
pub fn new(take: usize, user_id: &Uuid, ip_address: &str, ttl: Option<i64>) -> Self {
pub fn new(take: usize, username: &str, ip_address: &str, ttl: Option<i64>) -> Self {
let now = Utc::now();
Self {
session_id: csprng(take),
user_id: user_id.clone(),
username: username.to_string(),
ip_address: hash(&ip_address).unwrap(),
expires_at: match ttl {
Some(ttl) => Some(now + chrono::Duration::seconds(ttl)),
@@ -41,16 +37,15 @@ impl Session {
}
}
pub async fn store(&self) -> ApiResult<()> {
let mut conn = redis_async_connection().await?;
pub async fn store(&self, state: &AppState) -> ApiResult<()> {
let key = self.session_id.clone();
let value = serde_json::to_string(self)?;
let result: RedisResult<()> = match self.expires_at {
let result: CoreResult<()> = match self.expires_at {
Some(expires_at) => {
let ttl = expires_at.timestamp() - Utc::now().timestamp();
conn.set_ex(key, &value, ttl as u64).await
state.set_ex(&key, &value, ttl as u64).await
}
None => conn.set(key, value).await,
None => state.set(&key, &value).await,
};
match result {
Ok(_) => Ok(()),
@@ -58,43 +53,33 @@ impl Session {
}
}
pub async fn get(session_id: &str) -> ApiResult<Self> {
let mut conn = redis_async_connection().await?;
let result: RedisResult<Option<String>> = conn.get(session_id).await;
pub async fn get(state: &AppState, session_id: &str) -> ApiResult<Self> {
let result: Option<String> = state.get(session_id).await?;
match result {
Ok(Some(value)) => Ok(serde_json::from_str(&value)?),
Ok(None) => Err(Error::new(401, format!("Missing session {}", session_id))),
Err(err) => Err(err.into()),
Some(value) => Ok(serde_json::from_str(&value)?),
None => Err(Error::new(401, format!("Missing session {}", session_id))),
}
}
pub async fn replace(session_id: &str, ip_address: &str) -> ApiResult<Self> {
let mut session = Self::verify(session_id, ip_address).await?;
pub async fn replace(state: &AppState, session_id: &str, ip_address: &str) -> ApiResult<Self> {
let mut session = Self::verify(state, session_id, ip_address).await?;
let session_id_owned = session_id.to_owned();
task::spawn(async move {
if let Err(err) = Self::delete(&session_id_owned).await {
log::error!(
"Error deleting old session in replace session call: {}",
err
);
};
});
session = Session::default(&session.user_id, ip_address);
session.store().await?;
Self::delete(state, &session_id_owned).await?;
session = Session::default(&session.username, ip_address);
session.store(state).await?;
Ok(session)
}
pub async fn delete(session_id: &str) -> ApiResult<()> {
let mut conn = redis_async_connection().await?;
let result: RedisResult<()> = conn.del(session_id).await;
pub async fn delete(state: &AppState, session_id: &str) -> ApiResult<()> {
let result: CoreResult<()> = state.del(session_id).await;
match result {
Ok(_) => Ok(()),
Err(err) => Err(err.into()),
}
}
pub async fn verify(session_id: &str, ip_address: &str) -> ApiResult<Self> {
let session = Self::get(session_id).await?;
pub async fn verify(state: &AppState, session_id: &str, ip_address: &str) -> ApiResult<Self> {
let session = Self::get(state, session_id).await?;
// Check if the IP Address matches the Session's IP Address
if verify_hash(ip_address, &session.ip_address) {
@@ -104,7 +89,7 @@ impl Session {
}
}
pub fn cookie(&self) -> Cookie {
pub fn cookie(&self) -> Cookie<'_> {
let expires_at = match self.expires_at {
Some(expires_at) => expires_at.timestamp(),
None => DEFAULT_SESSION_TTL,
@@ -120,8 +105,8 @@ impl Session {
if let Ok(environment) = std::env::var("ENVIRONMENT") {
if environment == "development" || environment == "dev" {
log::trace!(
"Session cookie [User ID: {}]: {}",
self.user_id,
"Session cookie [User: {}]: {}",
self.username,
self.session_id
);
cookie.set_secure(false);
@@ -132,7 +117,7 @@ impl Session {
cookie
}
pub fn expiration_cookie(&self) -> Cookie {
pub fn expiration_cookie(&self) -> Cookie<'_> {
let expires_at = match self.expires_at {
Some(expires_at) => expires_at.timestamp(),
None => DEFAULT_SESSION_TTL,
@@ -148,8 +133,8 @@ impl Session {
if let Ok(environment) = std::env::var("ENVIRONMENT") {
if environment == "development" || environment == "dev" {
log::trace!(
"Session expiration cookie [User ID: {}]: {}",
self.user_id,
"Session expiration cookie [User: {}]: {}",
self.username,
self.session_id
);
cookie.set_secure(false);

133
crates/api/src/error.rs Normal file
View File

@@ -0,0 +1,133 @@
use actix_web::http::StatusCode;
use actix_web::{HttpResponse, ResponseError};
use log::warn;
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::fmt;
use lib::error::{CoreError, CoreErrorKind};
pub type ApiResult<T> = Result<T, Error>;
#[derive(Debug, Deserialize, Serialize)]
pub struct Error {
pub status: u16,
pub details: String,
}
impl Error {
pub fn new(status: u16, details: String) -> Self {
Self {
status,
details,
}
}
pub fn to_http_response(&self) -> HttpResponse {
let status = StatusCode::from_u16(self.status).unwrap_or_else(|err| {
warn!("{}", err);
StatusCode::INTERNAL_SERVER_ERROR
});
HttpResponse::build(status).body(self.details.to_string())
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(self.details.as_str())
}
}
impl std::error::Error for Error {
fn description(&self) -> &str {
&self.details
}
}
impl ResponseError for Error {
fn error_response(&self) -> HttpResponse {
let status =
StatusCode::from_u16(self.status).unwrap_or_else(|_| StatusCode::INTERNAL_SERVER_ERROR);
let status_code = status.as_u16();
let details = match status_code {
401 => String::from("Unauthorized"),
code if code < 500 => self.details.clone(),
_ => {
log::error!("Internal server error: {}", self.details);
String::from("Internal Server Error")
}
};
HttpResponse::build(status).json(json!({ "status": status_code, "details": details }))
}
}
impl From<std::io::Error> for Error {
fn from(error: std::io::Error) -> Self {
Self::new(500, format!("Unknown IO error: {:?}", error))
}
}
impl From<std::env::VarError> for Error {
fn from(error: std::env::VarError) -> Self {
Self::new(
500,
format!("Unknown environment variable error: {:?}", error),
)
}
}
impl From<serde_json::Error> for Error {
fn from(error: serde_json::Error) -> Self {
Self::new(500, format!("Unknown serde_json error: {:?}", error))
}
}
impl From<argon2::password_hash::Error> for Error {
fn from(error: argon2::password_hash::Error) -> Self {
Self::new(500, format!("Unknown argon2 error: {:?}", error))
}
}
impl From<lettre::address::AddressError> for Error {
fn from(error: lettre::address::AddressError) -> Self {
Error::new(500, error.to_string())
}
}
impl From<lettre::error::Error> for Error {
fn from(error: lettre::error::Error) -> Self {
Error::new(500, error.to_string())
}
}
impl From<lettre::transport::smtp::Error> for Error {
fn from(error: lettre::transport::smtp::Error) -> Self {
Error::new(500, error.to_string())
}
}
impl From<String> for Error {
fn from(error: String) -> Self {
Self::new(500, error)
}
}
impl From<CoreError> for Error {
fn from(error: CoreError) -> Self {
match error.kind {
CoreErrorKind::NotFound => Self::new(404, error.to_string()),
CoreErrorKind::InvalidInput => Self::new(400, error.to_string()),
CoreErrorKind::Conflict => Self::new(409, error.to_string()),
CoreErrorKind::Unauthorized => Self::new(401, error.to_string()),
CoreErrorKind::Forbidden => Self::new(403, error.to_string()),
CoreErrorKind::PreconditionFailed => Self::new(412, error.to_string()),
CoreErrorKind::Timeout => Self::new(408, error.to_string()),
CoreErrorKind::Cancelled => Self::new(499, error.to_string()),
CoreErrorKind::Unavailable => Self::new(503, error.to_string()),
CoreErrorKind::Internal => Self::new(500, error.to_string()),
CoreErrorKind::External => Self::new(502, error.to_string()),
_ => Self::new(500, error.to_string()),
}
}
}

View File

@@ -1,55 +1,46 @@
use crate::account::hash;
use crate::users::{ADMIN_ROLE, User};
use lib::accounts::{User, ADMIN_ROLE, hash};
use actix_cors::Cors;
use actix_web::{App, HttpServer, middleware::Logger, web};
use dotenv::from_filename;
use reqwest::Certificate;
use std::env;
use std::time::Duration;
use utoipa::openapi::SecurityRequirement;
use utoipa::openapi::security::{ApiKey, ApiKeyValue, SecurityScheme};
use utoipa::openapi::{Contact, SecurityRequirement};
use utoipa_actix_web::{AppExt, scope};
use utoipa_swagger_ui::{Config, SwaggerUi};
use uuid::Uuid;
use lib::state::AppState;
mod account;
mod airports;
mod db;
mod accounts;
mod error;
mod metars;
mod scheduler;
mod routes;
mod smtp;
mod system;
mod users;
#[derive(Debug, Clone)]
struct AppState {
client: reqwest::Client,
}
mod utils;
#[actix_web::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
initialize_environment()?;
db::initialize().await?;
// scheduler::update_airports();
let state = AppState::new().await?;
// Initialize admin user
let admin_username = env::var("ADMIN_USERNAME");
let admin_email = env::var("ADMIN_EMAIL");
let admin_password = env::var("ADMIN_PASSWORD");
if admin_email.is_ok() && admin_password.is_ok() {
if admin_username.is_ok() && admin_email.is_ok() && admin_password.is_ok() {
let username = admin_username.unwrap();
let email = admin_email.unwrap();
if User::select_by_email(&email).await.is_none() {
if User::select_by_email(&state.pool, &email).await.is_none() {
log::debug!("Creating default administrator");
let password = admin_password.unwrap();
let password_hash = hash(&password)?;
if email == "admin@example.com" || password == "changeme" {
log::warn!(
"Default admin credentials are in use, update the ADMIN_EMAIL and ADMIN_PASSWORD."
"Default admin credentials are in use, update the ADMIN_USERNAME, ADMIN_EMAIL, and ADMIN_PASSWORD."
);
}
let admin_user = User {
id: Uuid::new_v4(),
email,
username,
email: Some(email),
email_verified: true,
password_hash,
role: ADMIN_ROLE.to_string(),
@@ -59,7 +50,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
updated_at: Default::default(),
created_at: Default::default(),
};
match admin_user.insert().await {
match admin_user.insert(&state.pool).await {
Ok(_) => log::debug!("Default administrator was successfully created"),
Err(err) => {
log::warn!("{}", err);
@@ -68,24 +59,6 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
}
}
let mut client_builder = reqwest::Client::builder()
.timeout(Duration::from_secs(10))
.tls_built_in_root_certs(true);
if let Ok(val) = env::var("NGINX_SSL_ENABLED") {
if val == "true" {
let certificate_path = env::var("SSL_CA_PATH")?;
let certificate_data = std::fs::read(certificate_path)?;
let certificate = Certificate::from_pem(&certificate_data)?;
client_builder = client_builder.add_root_certificate(certificate);
}
}
let client = client_builder
.build()
.expect("Failed to create reqwest client");
let state = AppState { client };
let host = "0.0.0.0";
let port = env::var("API_PORT").unwrap_or("5000".to_string());
@@ -103,22 +76,19 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
.into_utoipa_app()
.service(
scope::scope("/api")
.configure(airports::init_routes)
.configure(metars::init_routes)
.configure(account::init_routes)
.configure(users::init_routes)
.configure(routes::init_routes)
.configure(system::init_routes),
)
.split_for_parts();
let version = env::var("CARGO_PKG_VERSION").unwrap();
let version = env!("CARGO_PKG_VERSION");
api.info.title = "Aviation Data".to_string();
api.info.description = None;
api.info.description = Some("This documentation describe the Aviation Data API".to_string());
api.info.terms_of_service = None;
api.info.contact = None;
api.info.license = None;
api.info.version = version;
api.info.version = version.to_string();
let session_scheme = SecurityScheme::ApiKey(ApiKey::Cookie(ApiKeyValue::new("session")));
let mut components = api.components.take().unwrap_or_default();
@@ -126,10 +96,13 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
.security_schemes
.insert("session_auth".to_string(), session_scheme);
api.components = Some(components);
// api.security = Some(vec![SecurityRequirement::new("session_auth", [""])]);
api.security = Some(vec![SecurityRequirement::default()]);
app.service(SwaggerUi::new("/swagger/{_:.*}").url("/api-docs/openapi.json", api))
app.service(
SwaggerUi::new("/swagger/{_:.*}")
.url("/api-docs/openapi.json", api)
.config(Config::default().use_base_layout()),
)
})
.bind(format!("{}:{}", host, port))
{
@@ -150,8 +123,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
}
fn initialize_environment() -> std::io::Result<()> {
fn init_dir(directory: &str) -> std::io::Result<()> {
// Iterate over files in the current directory
for entry in std::fs::read_dir(".")? {
for entry in std::fs::read_dir(directory)? {
let entry = entry?;
let path = entry.path();
@@ -167,6 +141,11 @@ fn initialize_environment() -> std::io::Result<()> {
}
}
}
Ok(())
}
init_dir("..")?;
init_dir(".")?;
env_logger::init_from_env(env_logger::Env::default().filter_or("RUST_LOG", "warn,api=info"));
Ok(())

View File

@@ -1,21 +1,16 @@
use crate::{
account::{SESSION_COOKIE_NAME, Session, verify_hash},
error::Error,
users::{LoginRequest, RegisterRequest, User, UserResponse},
};
use actix_web::{HttpRequest, HttpResponse, ResponseError, get, post, put, web};
use lib::accounts::{csprng, LoginRequest, RegisterRequest, UpdateUser, User, UserResponse, UserFavorite, verify_hash};
use actix_web::{HttpRequest, HttpResponse, ResponseError, delete, get, post, put, web};
use serde::Deserialize;
use std::fs;
use utoipa::ToSchema;
use utoipa_actix_web::scope;
use utoipa_actix_web::service_config::ServiceConfig;
use crate::account::email_token::{EmailToken, send_confirm_email, send_password_reset_email};
use crate::account::{Auth, csprng};
use crate::users::UpdateUser;
use lib::error::CoreErrorKind;
use lib::state::AppState;
use crate::accounts::{send_confirm_email, send_password_reset_email, Auth, EmailToken, Session, SESSION_COOKIE_NAME};
use crate::error::Error;
#[utoipa::path(
tag = "Account",
tag = "account",
request_body(
content = RegisterRequest, content_type = "application/json"
),
@@ -25,33 +20,35 @@ use crate::users::UpdateUser;
)
)]
#[post("/register")]
async fn register(user: web::Json<RegisterRequest>, req: HttpRequest) -> HttpResponse {
async fn register(state: web::Data<AppState>, user: web::Json<RegisterRequest>, req: HttpRequest) -> HttpResponse {
let register_user = user.into_inner();
let username = register_user.username.clone();
let email = register_user.email.clone();
let ip_address = req.peer_addr().unwrap().ip().to_string();
let insert_user: User = match register_user.to_user() {
let insert_user: User = match register_user.to_user().map_err(Error::from) {
Ok(user) => user,
Err(err) => return ResponseError::error_response(&err),
};
match insert_user.insert().await {
match insert_user.insert(&state.pool).await.map_err(Error::from) {
Ok(user) => {
let user_response: UserResponse = user.into();
log::info!(
"Successful user registration [Email: {}] [IP Address: {}]",
email,
"Successful user registration [User: {}] [IP Address: {}]",
username,
ip_address
);
// Send confirmation email
let token = csprng(128);
let email_token = EmailToken::new(email.clone(), token, &ip_address);
if let Err(err) = email_token.store(86400).await {
return ResponseError::error_response(&err);
}
if let Err(err) = send_confirm_email(&email, &email_token, &ip_address) {
return ResponseError::error_response(&Error::new(500, err.to_string()));
if let Some(email) = email {
if !email.is_empty() {
tokio::task::spawn_local(async move {
if let Err(err) = send_confirm_email(&state, &email, &ip_address).await {
log::error!("Failed to send confirmation email: {}", err);
};
});
}
}
HttpResponse::Created().json(user_response)
}
@@ -59,212 +56,47 @@ async fn register(user: web::Json<RegisterRequest>, req: HttpRequest) -> HttpRes
// Obfuscate the service error message to prevent leaking database details
if err.status == 409 {
log::warn!(
"Duplicate user registration attempt [Email: {}] [IP Address: {}]",
email,
"Duplicate user registration attempt [User: {}] [IP Address: {}]",
username,
ip_address
);
HttpResponse::Conflict().finish()
} else {
log::error!("Failed to register user [Email: {}]: {}", email, err);
log::error!("Failed to register user [User: {}]: {}", username, err);
ResponseError::error_response(&err)
}
}
}
}
#[utoipa::path(
tag = "Account",
request_body(
content = LoginRequest, content_type = "application/json"
),
responses(
(status = 200, description = "Successful Response", body = UserResponse),
),
)]
#[post("/login")]
async fn login(request: web::Json<LoginRequest>, req: HttpRequest) -> HttpResponse {
let email = &request.email;
let ip_address = req.peer_addr().unwrap().ip().to_string();
let query_user = match User::select_by_email(&email).await {
Some(query_user) => query_user,
None => return HttpResponse::Unauthorized().finish(),
};
if verify_hash(&request.password, &query_user.password_hash) {
// Create a session
let session = Session::default(&query_user.id, &ip_address);
let session_cookie = session.cookie();
let session_exp_cookie = session.expiration_cookie();
// Save the session to the database
if let Err(err) = session.store().await {
log::error!(
"Login attempt failure [Email: {}] [IP Address: {}]: {}",
email,
ip_address,
err
);
return ResponseError::error_response(&Error::new(500, err.to_string()));
}
log::info!(
"Successful login attempt [Email: {}] [IP Address: {}]",
email,
ip_address
);
let user_response: UserResponse = query_user.into();
HttpResponse::Ok()
.cookie(session_cookie)
.cookie(session_exp_cookie)
.json(user_response)
} else {
log::error!(
"Invalid login attempt [Email: {}] [IP Address: {}]",
email,
ip_address
);
HttpResponse::Unauthorized()
.cookie(Session::empty_cookie())
.cookie(Session::empty_expiration_cookie())
.finish()
}
}
#[utoipa::path(
tag = "Account",
responses(
(status = 200, description = "Successful Response"),
(status = 401, description = "Unauthorized"),
),
security(
("session_auth" = [])
)
)]
#[post("/logout")]
async fn logout(req: HttpRequest, auth: Auth) -> HttpResponse {
let email = auth.user.email;
let ip_address = req.peer_addr().unwrap().ip().to_string();
// Delete the session from the store
match req.cookie(SESSION_COOKIE_NAME) {
Some(cookie) => {
let session_id = cookie.value().to_string();
if let Err(err) = Session::delete(&session_id).await {
log::error!(
"Logout attempt failure [Email: {}] [IP Address: {}]: {}",
email,
ip_address,
err
);
return ResponseError::error_response(&Error::new(500, err.to_string()));
}
}
None => {
log::error!(
"Invalid logout attempt [Email: {}] [IP Address: {}]",
email,
ip_address
);
return ResponseError::error_response(&Error::new(400, "Invalid session".to_string()));
}
}
log::info!(
"Successful logout attempt [Email: {}] [IP Address: {}]",
email,
ip_address
);
HttpResponse::Ok()
.cookie(Session::empty_cookie())
.cookie(Session::empty_expiration_cookie())
.finish()
}
#[utoipa::path(
tag = "Account",
responses(
(status = 200, description = "Successful Response", body = UserResponse),
(status = 401, description = "Unauthorized"),
),
security(
("session_auth" = [])
)
)]
#[get("/profile")]
async fn get_profile(req: HttpRequest) -> HttpResponse {
let ip_address = req.peer_addr().unwrap().ip().to_string();
// Verify a session cookie exists
match req.cookie(SESSION_COOKIE_NAME) {
// Validate the session
Some(cookie) => {
let session_id = cookie.value().to_string();
let session = match Session::get(&session_id).await {
Ok(session) => session,
Err(_) => {
log::error!(
"Invalid profile attempt [Session: {}] [IP Address: {}]",
session_id,
ip_address
);
return HttpResponse::Unauthorized()
.cookie(Session::empty_cookie())
.cookie(Session::empty_expiration_cookie())
.finish();
}
};
let id = &session.user_id;
let query_user = match User::select(&id).await {
Some(query_user) => query_user,
None => {
return HttpResponse::Unauthorized()
.cookie(Session::empty_cookie())
.cookie(Session::empty_expiration_cookie())
.finish();
}
};
let user_response: UserResponse = query_user.into();
let session_cookie = session.cookie();
let session_exp_cookie = session.expiration_cookie();
log::info!(
"Successful profile attempt [ID: {}] [IP Address: {}]",
id,
ip_address
);
HttpResponse::Ok()
.cookie(session_cookie)
.cookie(session_exp_cookie)
.json(user_response)
}
None => HttpResponse::Unauthorized()
.cookie(Session::empty_cookie())
.cookie(Session::empty_expiration_cookie())
.finish(),
}
}
#[derive(Debug, Deserialize, ToSchema)]
struct TokenRequest {
struct ConfirmEmail {
token: String,
}
#[utoipa::path(
tag = "Account",
tag = "account",
request_body(
content = TokenRequest, content_type = "application/json"
content = ConfirmEmail, content_type = "application/json"
),
responses(
(status = 200, description = "Successful Response", body = UserResponse),
(status = 404, description = "Not Found"),
(status = 409, description = "Conflict"),
),
)]
#[post("/profile/confirm")]
async fn confirm_profile(request: web::Json<TokenRequest>, req: HttpRequest) -> HttpResponse {
#[post("/register/confirm")]
async fn confirm_email_registration(
state: web::Data<AppState>,
request: web::Json<ConfirmEmail>,
req: HttpRequest,
) -> HttpResponse {
let ip_address = req.peer_addr().unwrap().ip().to_string();
let token = &request.token;
let email_token = match EmailToken::get(token).await {
let email_token = match EmailToken::get(&state, token).await {
Ok(password_reset) => {
if let Err(err) = EmailToken::delete(&password_reset.token).await {
if let Err(err) = EmailToken::delete(&state, &password_reset.token).await {
return ResponseError::error_response(&err);
};
password_reset
@@ -274,7 +106,7 @@ async fn confirm_profile(request: web::Json<TokenRequest>, req: HttpRequest) ->
}
};
match User::select_by_email(&email_token.email).await {
match User::select_by_email(&state.pool, &email_token.email).await {
Some(user) => {
let update_user = UpdateUser {
email: None,
@@ -286,7 +118,7 @@ async fn confirm_profile(request: web::Json<TokenRequest>, req: HttpRequest) ->
avatar: None,
};
match update_user.update(&user.id).await {
match update_user.update(&state.pool, &user.username).await.map_err(Error::from) {
Ok(user) => {
let response: UserResponse = user.into();
log::info!(
@@ -312,7 +144,215 @@ async fn confirm_profile(request: web::Json<TokenRequest>, req: HttpRequest) ->
}
#[utoipa::path(
tag = "Account",
tag = "account",
responses(
(status = 200, description = "Successful Response"),
(status = 404, description = "Not Found"),
),
security(
("session_auth" = [])
)
)]
#[post("/register/email")]
async fn resend_email_verification(state: web::Data<AppState>, req: HttpRequest, auth: Auth) -> HttpResponse {
let email = auth.user.email;
let ip_address = req.peer_addr().unwrap().ip().to_string();
match email {
Some(email) => {
let user = match User::select_by_email(&state.pool, &email).await {
Some(query_user) => query_user,
None => return HttpResponse::Unauthorized().finish(),
};
// Cannot reverify if the user is already verified
if user.email_verified {
return HttpResponse::Conflict().finish();
}
// Send reverify confirmation email
if let Err(err) = send_confirm_email(&state, &email, &ip_address).await {
log::error!("Failed to send reverify confirmation email: {}", err);
return HttpResponse::InternalServerError().finish();
};
HttpResponse::Ok().finish()
}
None => HttpResponse::NotFound().finish(),
}
}
#[utoipa::path(
tag = "account",
request_body(
content = LoginRequest, content_type = "application/json"
),
responses(
(status = 200, description = "Successful Response", body = UserResponse),
),
)]
#[post("/login")]
async fn login(state: web::Data<AppState>, request: web::Json<LoginRequest>, req: HttpRequest) -> HttpResponse {
let username = &request.username;
let ip_address = req.peer_addr().unwrap().ip().to_string();
let query_user = match User::select(&state.pool, &username).await {
Some(query_user) => query_user,
None => return HttpResponse::Unauthorized().finish(),
};
if verify_hash(&request.password, &query_user.password_hash) {
// Create a session
let session = Session::default(&query_user.username, &ip_address);
let session_cookie = session.cookie();
let session_exp_cookie = session.expiration_cookie();
// Save the session to the database
if let Err(err) = session.store(&state).await {
log::error!(
"Login attempt failure [User: {}] [IP Address: {}]: {}",
username,
ip_address,
err
);
return ResponseError::error_response(&Error::new(500, err.to_string()));
}
log::info!(
"Successful login attempt [User: {}] [IP Address: {}]",
username,
ip_address
);
let user_response: UserResponse = query_user.into();
HttpResponse::Ok()
.cookie(session_cookie)
.cookie(session_exp_cookie)
.json(user_response)
} else {
log::error!(
"Invalid login attempt [User: {}] [IP Address: {}]",
username,
ip_address
);
HttpResponse::Unauthorized()
.cookie(Session::empty_cookie())
.cookie(Session::empty_expiration_cookie())
.finish()
}
}
#[utoipa::path(
tag = "account",
responses(
(status = 200, description = "Successful Response"),
(status = 401, description = "Unauthorized"),
),
security(
("session_auth" = [])
)
)]
#[post("/logout")]
async fn logout(state: web::Data<AppState>, req: HttpRequest, auth: Auth) -> HttpResponse {
let username = auth.user.username;
let ip_address = req.peer_addr().unwrap().ip().to_string();
// Delete the session from the store
match req.cookie(SESSION_COOKIE_NAME) {
Some(cookie) => {
let session_id = cookie.value().to_string();
if let Err(err) = Session::delete(&state, &session_id).await {
log::error!(
"Logout attempt failure [User: {}] [IP Address: {}]: {}",
username,
ip_address,
err
);
return ResponseError::error_response(&Error::new(500, err.to_string()));
}
}
None => {
log::error!(
"Invalid logout attempt [User: {}] [IP Address: {}]",
username,
ip_address
);
return ResponseError::error_response(&Error::new(400, "Invalid session".to_string()));
}
}
log::info!(
"Successful logout attempt [User: {}] [IP Address: {}]",
username,
ip_address
);
HttpResponse::Ok()
.cookie(Session::empty_cookie())
.cookie(Session::empty_expiration_cookie())
.finish()
}
#[utoipa::path(
tag = "account",
responses(
(status = 200, description = "Successful Response", body = UserResponse),
(status = 401, description = "Unauthorized"),
),
security(
("session_auth" = [])
)
)]
#[get("/profile")]
async fn get_profile(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
let ip_address = req.peer_addr().unwrap().ip().to_string();
// Verify a session cookie exists
match req.cookie(SESSION_COOKIE_NAME) {
// Validate the session
Some(cookie) => {
let session_id = cookie.value().to_string();
let session = match Session::get(&state, &session_id).await {
Ok(session) => session,
Err(_) => {
log::error!(
"Invalid profile attempt [Session: {}] [IP Address: {}]",
session_id,
ip_address
);
return HttpResponse::Unauthorized()
.cookie(Session::empty_cookie())
.cookie(Session::empty_expiration_cookie())
.finish();
}
};
let username = &session.username;
let query_user = match User::select(&state.pool, &username).await {
Some(query_user) => query_user,
None => {
return HttpResponse::Unauthorized()
.cookie(Session::empty_cookie())
.cookie(Session::empty_expiration_cookie())
.finish();
}
};
let user_response: UserResponse = query_user.into();
let session_cookie = session.cookie();
let session_exp_cookie = session.expiration_cookie();
log::info!(
"Successful profile attempt [User: {}] [IP Address: {}]",
username,
ip_address
);
HttpResponse::Ok()
.cookie(session_cookie)
.cookie(session_exp_cookie)
.json(user_response)
}
None => HttpResponse::Unauthorized()
.cookie(Session::empty_cookie())
.cookie(Session::empty_expiration_cookie())
.finish(),
}
}
#[utoipa::path(
tag = "account",
responses(
(status = 200, description = "Successful Response"),
(status = 401, description = "Unauthorized"),
@@ -322,14 +362,14 @@ async fn confirm_profile(request: web::Json<TokenRequest>, req: HttpRequest) ->
)
)]
#[post("/session")]
async fn session_refresh(req: HttpRequest) -> HttpResponse {
async fn session_refresh(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
let ip_address = req.peer_addr().unwrap().ip().to_string();
// Verify a session cookie exists
match req.cookie(SESSION_COOKIE_NAME) {
// Validate the session
Some(cookie) => {
let session_id = cookie.value().to_string();
let session = match Session::replace(&session_id, &ip_address).await {
let session = match Session::replace(&state, &session_id, &ip_address).await {
Ok(session) => session,
Err(_) => {
log::error!(
@@ -343,13 +383,13 @@ async fn session_refresh(req: HttpRequest) -> HttpResponse {
.finish();
}
};
let id = &session.user_id;
let username = &session.username;
let session_cookie = session.cookie();
let session_exp_cookie = session.expiration_cookie();
log::info!(
"Successful session validate attempt [ID: {}] [IP Address: {}]",
id,
"Successful session validate attempt [User: {}] [IP Address: {}]",
username,
ip_address
);
HttpResponse::Ok()
@@ -365,14 +405,14 @@ async fn session_refresh(req: HttpRequest) -> HttpResponse {
}
#[derive(Debug, Deserialize, ToSchema)]
struct PasswordRequest {
struct ChangePassword {
password: String,
}
#[utoipa::path(
tag = "Account",
tag = "account",
request_body(
content = PasswordRequest, content_type = "application/json"
content = ChangePassword, content_type = "application/json"
),
responses(
(status = 200, description = "Successful Response", body = UserResponse),
@@ -384,14 +424,15 @@ struct PasswordRequest {
)]
#[put("/password")]
async fn change_password(
request: web::Json<PasswordRequest>,
state: web::Data<AppState>,
request: web::Json<ChangePassword>,
req: HttpRequest,
auth: Auth,
) -> HttpResponse {
let ip_address = req.peer_addr().unwrap().ip().to_string();
let id = auth.user.id;
let username = auth.user.username;
if let None = User::select(&id).await {
if let None = User::select(&state.pool, &username).await {
return HttpResponse::Unauthorized().finish();
};
@@ -405,20 +446,20 @@ async fn change_password(
avatar: None,
};
match update_user.update(&id).await {
match update_user.update(&state.pool, &username).await.map_err(Error::from) {
Ok(user) => {
let response: UserResponse = user.into();
log::info!(
"Successful password change attempt [ID: {}] [IP Address: {}]",
&id,
"Successful password change attempt [User: {}] [IP Address: {}]",
&username,
ip_address
);
HttpResponse::Ok().json(response)
}
Err(err) => {
log::error!(
"Invalid password change attempt [ID: {}] [IP Address: {}]: {}",
&id,
"Invalid password change attempt [User: {}] [IP Address: {}]: {}",
&username,
ip_address,
err
);
@@ -428,62 +469,70 @@ async fn change_password(
}
#[derive(Debug, Deserialize, ToSchema)]
struct EmailRequest {
struct PasswordReset {
email: String,
}
#[utoipa::path(
tag = "Account",
tag = "account",
request_body(
content = EmailRequest, content_type = "application/json"
content = PasswordReset, content_type = "application/json"
),
responses(
(status = 200, description = "Successful Response"),
)
)]
#[post("/password/reset")]
async fn reset_password(request: web::Json<EmailRequest>, req: HttpRequest) -> HttpResponse {
async fn reset_password(state: web::Data<AppState>, request: web::Json<PasswordReset>, req: HttpRequest) -> HttpResponse {
let email = &request.email;
let ip_address = req.peer_addr().unwrap().ip().to_string();
let token = csprng(128);
// Silently return if the user does not exist
if let None = User::select_by_email(&email).await {
// Silently return if the user's email does not exist
if let None = User::select_by_email(&state.pool, &email).await {
return HttpResponse::Ok().finish();
};
let email_token = EmailToken::new(email.clone(), token, &ip_address);
if let Err(err) = email_token.store(86400).await {
if let Err(err) = email_token.store(&state, 86400).await {
return ResponseError::error_response(&err);
}
if let Err(err) = send_password_reset_email(email, &email_token, &ip_address) {
if let Err(err) = send_password_reset_email(email, &email_token, &ip_address).await {
return ResponseError::error_response(&Error::new(500, err.to_string()));
};
HttpResponse::Ok().finish()
}
#[derive(Debug, Deserialize, ToSchema)]
struct ConfirmPasswordReset {
token: String,
password: String,
}
#[utoipa::path(
tag = "Account",
tag = "account",
request_body(
content = TokenRequest, content_type = "application/json"
content = ConfirmPasswordReset, content_type = "application/json"
),
responses(
(status = 200, description = "Successful Response"),
(status = 404, description = "Not Found"),
)
)]
#[post("/password/validate")]
async fn validate_reset_password(
request: web::Json<TokenRequest>,
#[post("/password/reset/confirm")]
async fn confirm_password_reset(
state: web::Data<AppState>,
request: web::Json<ConfirmPasswordReset>,
req: HttpRequest,
) -> HttpResponse {
let ip_address = req.peer_addr().unwrap().ip().to_string();
// TODO
let _ip_address = req.peer_addr().unwrap().ip().to_string();
let token = &request.token;
let email_token = match EmailToken::get(token).await {
let _email_token = match EmailToken::get(&state, token).await {
Ok(password_reset) => {
if let Err(err) = EmailToken::delete(&password_reset.token).await {
if let Err(err) = EmailToken::delete(&state, &password_reset.token).await {
return ResponseError::error_response(&err);
};
password_reset
@@ -496,17 +545,78 @@ async fn validate_reset_password(
HttpResponse::Ok().finish()
}
#[utoipa::path(
tag = "account",
responses(
(status = 200, description = "Successful Response"),
(status = 401, description = "Unauthorized"),
),
security(
("session_auth" = [])
)
)]
#[get("/profile/favorites")]
async fn get_favorites(state: web::Data<AppState>, auth: Auth) -> HttpResponse {
let username = auth.user.username;
match UserFavorite::select_all(&state.pool, &username).await.map_err(Error::from) {
Ok(favorites) => HttpResponse::Ok().json(favorites),
Err(err) => ResponseError::error_response(&err),
}
}
#[utoipa::path(
tag = "account",
responses(
(status = 200, description = "Successful Response"),
(status = 401, description = "Unauthorized"),
),
security(
("session_auth" = [])
)
)]
#[post("/profile/favorites/{icao}")]
async fn add_favorite(state: web::Data<AppState>, icao: web::Path<String>, auth: Auth) -> HttpResponse {
let username = auth.user.username;
match UserFavorite::insert(&state.pool, &username, &icao.into_inner()).await.map_err(Error::from) {
Ok(_) => HttpResponse::Ok().finish(),
Err(err) => ResponseError::error_response(&err),
}
}
#[utoipa::path(
tag = "account",
responses(
(status = 200, description = "Successful Response"),
(status = 401, description = "Unauthorized"),
),
security(
("session_auth" = [])
)
)]
#[delete("/profile/favorites/{icao}")]
async fn remove_favorite(state: web::Data<AppState>, icao: web::Path<String>, auth: Auth) -> HttpResponse {
let username = auth.user.username;
match UserFavorite::delete(&state.pool, &username, &icao.into_inner()).await.map_err(Error::from) {
Ok(_) => HttpResponse::Ok().finish(),
Err(err) => ResponseError::error_response(&err),
}
}
pub fn init_routes(config: &mut ServiceConfig) {
config.service(
scope::scope("/account")
.service(register)
.service(confirm_email_registration)
.service(resend_email_verification)
.service(login)
.service(logout)
.service(get_profile)
.service(confirm_profile)
.service(session_refresh)
.service(change_password)
.service(reset_password)
.service(validate_reset_password),
.service(confirm_password_reset)
.service(get_favorites)
.service(add_favorite)
.service(remove_favorite),
);
}

View File

@@ -1,30 +1,27 @@
use futures_util::stream::StreamExt as _;
use crate::airports::{AirportQuery, UpdateAirport};
use crate::users::ADMIN_ROLE;
use crate::{
AppState,
account::{Auth, verify_role},
airports::Airport,
db::Paged,
};
use lib::{accounts::ADMIN_ROLE, airports::{Airport, AirportQuery, UpdateAirport}};
use actix_multipart::Multipart;
use actix_web::{HttpRequest, HttpResponse, ResponseError, delete, get, post, put, web};
use utoipa::ToSchema;
use utoipa_actix_web::scope;
use utoipa_actix_web::service_config::ServiceConfig;
use lib::state::AppState;
use crate::accounts::Auth;
use crate::error::Error;
use crate::utils::Paged;
#[derive(ToSchema)]
#[allow(unused)]
struct UploadedFile {
struct FileUpload {
#[schema(value_type = String, format = Binary)]
file: Vec<u8>,
}
#[utoipa::path(
tag = "Airports",
tag = "airport",
request_body(
content = UploadedFile, content_type = "multipart/form-data"
content = FileUpload, content_type = "multipart/form-data"
),
responses(
(status = 200, description = "Successful import"),
@@ -35,9 +32,9 @@ struct UploadedFile {
)
)]
#[post("/import")]
async fn import_airports(mut payload: Multipart, auth: Auth) -> HttpResponse {
if let Err(err) = verify_role(&auth, ADMIN_ROLE) {
return ResponseError::error_response(&err);
async fn import_airports(state: web::Data<AppState>, mut payload: Multipart, auth: Auth) -> HttpResponse {
if let Err(err) = &auth.verify_role(ADMIN_ROLE).map_err(Error::from) {
return ResponseError::error_response(err);
};
while let Some(item) = payload.next().await {
@@ -68,7 +65,7 @@ async fn import_airports(mut payload: Multipart, auth: Auth) -> HttpResponse {
}
};
match Airport::insert_all(airports).await {
match Airport::insert_all(&state.pool, airports).await.map_err(Error::from) {
Ok(_) => {}
Err(err) => return ResponseError::error_response(&err),
};
@@ -77,7 +74,7 @@ async fn import_airports(mut payload: Multipart, auth: Auth) -> HttpResponse {
}
#[utoipa::path(
tag = "Airports",
tag = "airport",
params(
AirportQuery
),
@@ -86,7 +83,7 @@ async fn import_airports(mut payload: Multipart, auth: Auth) -> HttpResponse {
),
)]
#[get("")]
async fn get_airports(data: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
async fn get_airports(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
let mut query = match web::Query::<AirportQuery>::from_query(req.query_string()) {
Ok(q) => q.into_inner(),
Err(err) => {
@@ -95,7 +92,7 @@ async fn get_airports(data: web::Data<AppState>, req: HttpRequest) -> HttpRespon
}
};
let total = Airport::count(&query).await;
let total = Airport::count(&state.pool, &query).await;
let page = query.page.unwrap_or(1);
let mut limit = query.limit.unwrap_or(total as u32);
if limit > 1000 {
@@ -104,8 +101,7 @@ async fn get_airports(data: web::Data<AppState>, req: HttpRequest) -> HttpRespon
query.limit = Some(limit);
query.page = Some(page);
let client = &data.client;
match Airport::select_all(client, &query).await {
match Airport::select_all(&state.pool, &query).await.map_err(Error::from) {
Ok(airports) => HttpResponse::Ok().json(Paged {
data: airports,
page,
@@ -120,18 +116,14 @@ async fn get_airports(data: web::Data<AppState>, req: HttpRequest) -> HttpRespon
}
#[utoipa::path(
tag = "Airports",
tag = "airport",
responses(
(status = 200, description = "", body = Airport),
(status = 404, description = ""),
),
)]
#[get("/{icao}")]
async fn get_airport(
data: web::Data<AppState>,
icao: web::Path<String>,
req: HttpRequest,
) -> HttpResponse {
async fn get_airport(state: web::Data<AppState>, icao: web::Path<String>, req: HttpRequest) -> HttpResponse {
let metar = match web::Query::<AirportQuery>::from_query(req.query_string()) {
Ok(q) => q.metars.unwrap_or_else(|| false),
Err(err) => {
@@ -140,15 +132,14 @@ async fn get_airport(
}
};
let client = &data.client;
match Airport::select(client, &icao.into_inner(), metar).await {
match Airport::select(&state.pool, &icao.into_inner(), metar).await {
Some(airport) => HttpResponse::Ok().json(airport),
None => HttpResponse::NotFound().finish(),
}
}
#[utoipa::path(
tag = "Airports",
tag = "airport",
responses(
(status = 200, description = "", body = Airport),
(status = 401, description = ""),
@@ -159,12 +150,12 @@ async fn get_airport(
)
)]
#[post("")]
async fn insert_airport(airport: web::Json<Airport>, auth: Auth) -> HttpResponse {
let _ = match verify_role(&auth, ADMIN_ROLE) {
async fn insert_airport(state: web::Data<AppState>, airport: web::Json<Airport>, auth: Auth) -> HttpResponse {
let _ = match &auth.verify_role(ADMIN_ROLE) {
Ok(_) => {}
Err(err) => return ResponseError::error_response(&err),
Err(err) => return ResponseError::error_response(err),
};
match airport.insert().await {
match airport.insert(&state.pool).await.map_err(Error::from) {
Ok(a) => HttpResponse::Ok().json(a),
Err(err) => {
log::error!("{}", err);
@@ -174,7 +165,7 @@ async fn insert_airport(airport: web::Json<Airport>, auth: Auth) -> HttpResponse
}
#[utoipa::path(
tag = "Airports",
tag = "airport",
responses(
(status = 200, description = "", body = Airport),
(status = 401, description = ""),
@@ -185,15 +176,16 @@ async fn insert_airport(airport: web::Json<Airport>, auth: Auth) -> HttpResponse
)]
#[put("/{icao}")]
async fn update_airport(
state: web::Data<AppState>,
icao: web::Path<String>,
airport: web::Json<UpdateAirport>,
auth: Auth,
) -> HttpResponse {
let _ = match verify_role(&auth, ADMIN_ROLE) {
let _ = match &auth.verify_role(ADMIN_ROLE) {
Ok(_) => {}
Err(err) => return ResponseError::error_response(&err),
Err(err) => return ResponseError::error_response(err),
};
match Airport::update(&icao.into_inner(), &airport.into_inner()).await {
match Airport::update(&state.pool, &icao.into_inner(), &airport.into_inner()).await.map_err(Error::from) {
Ok(a) => HttpResponse::Ok().json(a),
Err(err) => {
log::error!("{}", err);
@@ -203,7 +195,7 @@ async fn update_airport(
}
#[utoipa::path(
tag = "Airports",
tag = "airport",
responses(
(status = 201, description = ""),
(status = 401, description = ""),
@@ -213,12 +205,12 @@ async fn update_airport(
)
)]
#[delete("")]
async fn delete_airports(auth: Auth) -> HttpResponse {
let _ = match verify_role(&auth, ADMIN_ROLE) {
async fn delete_airports(state: web::Data<AppState>, auth: Auth) -> HttpResponse {
let _ = match &auth.verify_role(ADMIN_ROLE) {
Ok(_) => {}
Err(err) => return ResponseError::error_response(&err),
Err(err) => return ResponseError::error_response(err),
};
match Airport::delete_all().await {
match Airport::delete_all(&state.pool).await.map_err(Error::from) {
Ok(_) => HttpResponse::NoContent().finish(),
Err(err) => {
log::error!("{}", err);
@@ -228,7 +220,7 @@ async fn delete_airports(auth: Auth) -> HttpResponse {
}
#[utoipa::path(
tag = "Airports",
tag = "airport",
responses(
(status = 201, description = ""),
(status = 401, description = ""),
@@ -238,12 +230,12 @@ async fn delete_airports(auth: Auth) -> HttpResponse {
)
)]
#[delete("/{icao}")]
async fn delete_airport(icao: web::Path<String>, auth: Auth) -> HttpResponse {
let _ = match verify_role(&auth, ADMIN_ROLE) {
async fn delete_airport(state: web::Data<AppState>, icao: web::Path<String>, auth: Auth) -> HttpResponse {
let _ = match &auth.verify_role(ADMIN_ROLE) {
Ok(_) => {}
Err(err) => return ResponseError::error_response(&err),
Err(err) => return ResponseError::error_response(err),
};
match Airport::delete(&icao.into_inner()).await {
match Airport::delete(&state.pool, &icao.into_inner()).await.map_err(Error::from) {
Ok(_) => HttpResponse::NoContent().finish(),
Err(err) => {
log::error!("{}", err);

View File

@@ -0,0 +1,94 @@
use crate::AppState;
use actix_web::{HttpRequest, HttpResponse, get, put, web};
use log::error;
use serde::Deserialize;
use utoipa::{IntoParams, ToSchema};
use utoipa_actix_web::scope;
use utoipa_actix_web::service_config::ServiceConfig;
use lib::metars::Metar;
use crate::accounts::Auth;
use crate::error::Error;
#[derive(Debug, Deserialize, ToSchema, IntoParams)]
#[into_params(parameter_in = Query)]
struct MetarQuery {
icaos: Option<String>,
}
#[utoipa::path(
tag = "metar",
params(
MetarQuery,
),
responses(
(status = 200, description = "Successful Response", body = [Metar]),
),
)]
#[get("")]
async fn find_all(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
let parameters = web::Query::<MetarQuery>::from_query(req.query_string()).unwrap();
let icao_option = &parameters.icaos;
if let None = icao_option {
let empty_metars: Vec<Metar> = vec![];
return HttpResponse::Ok().json(empty_metars);
}
let icao_string = match icao_option {
Some(i) => i,
None => return HttpResponse::UnprocessableEntity().body("Missing icaos parameter"),
};
let icaos: Vec<String> = icao_string.split(',').map(|s| s.to_uppercase()).collect();
let metars = match Metar::get_all_distinct(&state.pool, &icaos).await.map_err(Error::from) {
Ok(a) => a,
Err(err) => {
error!("{}", err);
return err.to_http_response();
}
};
HttpResponse::Ok().json(metars)
}
#[utoipa::path(
tag = "metar",
params(
MetarQuery,
),
responses(
(status = 200, description = "Successful Response", body = [Metar]),
(status = 401, description = "Unauthorized"),
),
security(
("session_auth" = [])
)
)]
#[put("")]
async fn refresh_metars(state: web::Data<AppState>, req: HttpRequest, _auth: Auth) -> HttpResponse {
let parameters = web::Query::<MetarQuery>::from_query(req.query_string()).unwrap();
let icao_option = &parameters.icaos;
if let None = icao_option {
let empty_metars: Vec<Metar> = vec![];
return HttpResponse::Ok().json(empty_metars);
}
let icao_string = match icao_option {
Some(i) => i,
None => return HttpResponse::UnprocessableEntity().body("Missing icaos parameter"),
};
let icaos: Vec<String> = icao_string.split(',').map(|s| s.to_uppercase()).collect();
let metars = match Metar::get_or_update_metars(&state, &icaos).await.map_err(Error::from) {
Ok(a) => a,
Err(err) => {
error!("{}", err);
return err.to_http_response();
}
};
HttpResponse::Ok().json(metars)
}
pub fn init_routes(config: &mut ServiceConfig) {
config.service(
scope::scope("/metars")
.service(find_all)
.service(refresh_metars),
);
}

View File

@@ -0,0 +1,12 @@
use utoipa_actix_web::service_config::ServiceConfig;
mod accounts;
mod airports;
mod metars;
pub fn init_routes(config: &mut ServiceConfig) {
config
.configure(accounts::init_routes)
.configure(airports::init_routes)
.configure(metars::init_routes);
}

View File

@@ -1,28 +1,36 @@
use crate::error::ApiResult;
use chrono::{Datelike, Utc};
use handlebars::Handlebars;
use lettre::message::header::ContentType;
use lettre::message::{Mailbox, MultiPart, SinglePart};
use lettre::transport::smtp::AsyncSmtpTransportBuilder;
use lettre::transport::smtp::authentication::Credentials;
use lettre::{Address, Message, SmtpTransport, Transport};
use serde::Serialize;
use std::path::Path;
use lettre::{Address, AsyncSmtpTransport, AsyncTransport, Message, Tokio1Executor};
use std::env;
use std::sync::OnceLock;
use std::{env, fs};
use std::time::Duration;
static MAILER: OnceLock<SmtpTransport> = OnceLock::new();
static MAILER: OnceLock<AsyncSmtpTransport<Tokio1Executor>> = OnceLock::new();
static FROM_ADDRESS: OnceLock<Mailbox> = OnceLock::new();
static REGISTRY: OnceLock<Handlebars> = OnceLock::new();
fn mailer() -> &'static SmtpTransport {
fn mailer() -> &'static AsyncSmtpTransport<Tokio1Executor> {
MAILER.get_or_init(|| {
let server = env::var("SMTP_SERVER").expect("SMTP_SERVER missing");
let username = env::var("SMTP_USERNAME").expect("SMTP_USERNAME missing");
let password = env::var("SMTP_PASSWORD").expect("SMTP_PASSWORD missing");
let port = env::var("SMTP_PORT").expect("SMTP_PORT missing");
let creds = Credentials::new(username, password);
SmtpTransport::relay(&server)
.expect("invalid SMTP_SERVER")
let builder: AsyncSmtpTransportBuilder;
if server == "localhost" || server == "127.0.0.1" {
builder = AsyncSmtpTransport::<Tokio1Executor>::builder_dangerous(&server);
log::warn!("Using a local SMTP server: {}", server);
} else {
builder = AsyncSmtpTransport::<Tokio1Executor>::relay(&server).expect("invalid SMTP_SERVER");
}
builder
.credentials(creds)
.port(port.parse().expect("SMTP_PORT invalid"))
.timeout(Some(Duration::from_secs(10)))
.build()
})
}
@@ -39,7 +47,7 @@ pub fn registry() -> &'static Handlebars<'static> {
REGISTRY.get_or_init(|| Handlebars::new())
}
pub fn send_email(to: &str, subject: &str, header: String, html: String) -> ApiResult<()> {
pub async fn send_email(to: &str, subject: &str, header: String, html: String) -> ApiResult<()> {
let to_address = to.parse::<Address>()?;
let to_mailbox = Mailbox::new(None, to_address);
@@ -63,6 +71,6 @@ pub fn send_email(to: &str, subject: &str, header: String, html: String) -> ApiR
)?;
// Send the email
mailer().send(&email)?;
mailer().send(email).await?;
Ok(())
}

View File

@@ -12,24 +12,20 @@ pub struct SystemInfo {
}
#[utoipa::path(
tag = "System",
tag = "system",
responses(
(status = 200, description = "Successful system info"),
)
)]
#[get("/info")]
async fn info() -> HttpResponse {
let mut healthy = true;
let version = match env::var("CARGO_PKG_VERSION") {
Ok(v) => v,
Err(_) => {
healthy = false;
String::from("unknown")
}
let healthy = true;
let version = env!("CARGO_PKG_VERSION");
let info = SystemInfo {
version: version.to_string(),
healthy,
};
let info = SystemInfo { version, healthy };
HttpResponse::Ok().json(info)
}

9
crates/api/src/utils.rs Normal file
View File

@@ -0,0 +1,9 @@
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
pub struct Paged<T> {
pub data: Vec<T>,
pub page: u32,
pub limit: u32,
pub total: i64,
}

24
crates/lib/Cargo.toml Normal file
View File

@@ -0,0 +1,24 @@
[package]
name = "lib"
version = "0.1.0"
edition = "2024"
[dependencies]
argon2 = "0.5.3"
chrono = { version = "0.4.42", features = ["serde"] }
log = "0.4.28"
rand = "0.9.2"
rand_chacha = "0.9.0"
serde = { version = "1.0.226", features = ["derive"] }
serde_json = "1.0.142"
sqlx = { version = "0.8.6", features = ["runtime-tokio", "postgres", "chrono", "uuid"] }
utoipa = { version = "5.4.0", features = ["chrono", "uuid", "actix_extras"] }
uuid = { version = "1.18.1", features = ["serde", "v4"] }
futures-util = "0.3.31"
flate2 = "1.1.2"
reqwest = "0.12.23"
regex = "1.11.2"
redis = { version = "0.32.5", features = ["tokio-comp", "connection-manager", "r2d2", "json"] }
governor = "0.10.1"
tokio = { version = "1.47.1", features = ["macros", "rt", "time"] }
rust-s3 = "0.37.0"

View File

@@ -65,8 +65,8 @@ CREATE TABLE IF NOT EXISTS metars (
CREATE INDEX ON metars (observation_time DESC);
CREATE TABLE IF NOT EXISTS users (
id UUID UNIQUE NOT NULL,
email TEXT NOT NULL,
username TEXT PRIMARY KEY NOT NULL,
email TEXT,
email_verified BOOLEAN NOT NULL DEFAULT false,
password_hash TEXT NOT NULL,
role TEXT NOT NULL,
@@ -74,6 +74,11 @@ CREATE TABLE IF NOT EXISTS users (
last_name TEXT NOT NULL,
avatar TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY(email)
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS user_airport_favorites (
username TEXT NOT NULL REFERENCES users(username) ON DELETE CASCADE,
icao TEXT NOT NULL REFERENCES airports(icao) ON DELETE CASCADE,
PRIMARY KEY (username, icao)
);

View File

@@ -0,0 +1,9 @@
mod password_requirements;
mod user;
mod user_favorites;
mod utils;
pub use password_requirements::*;
pub use user::*;
pub use user_favorites::*;
pub use utils::*;

View File

@@ -0,0 +1,24 @@
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PasswordRequirements {
pub max_length: Option<usize>,
pub min_length: Option<usize>,
pub lowercase_count: Option<usize>,
pub uppercase_count: Option<usize>,
pub numeric_count: Option<usize>,
pub special_count: Option<usize>,
}
impl Default for PasswordRequirements {
fn default() -> Self {
Self {
max_length: Some(128),
min_length: Some(6),
lowercase_count: None,
uppercase_count: None,
numeric_count: None,
special_count: None,
}
}
}

View File

@@ -1,30 +1,47 @@
use crate::db;
use crate::{account::hash, error::ApiResult};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
#[allow(unused_imports)] // Import is used in schema examples
use serde_json::json;
use sqlx::{Postgres, QueryBuilder};
use sqlx::{Pool, Postgres, QueryBuilder};
use utoipa::ToSchema;
use uuid::Uuid;
use crate::accounts::hash;
use crate::error::CoreResult;
pub const ADMIN_ROLE: &str = "ADMIN";
pub const USER_ROLE: &str = "USER";
const TABLE_NAME: &str = "users";
#[derive(Debug, Deserialize, ToSchema)]
#[schema(
example = json!(
{
"email": "user",
"email": "user@example.com",
"password": "changeme",
"firstName": "firstname",
"lastName": "lastname"
}
)
)]
pub struct RegisterRequest {
pub email: String,
pub username: String,
pub email: Option<String>,
pub password: String,
#[serde(rename = "firstName")]
pub first_name: String,
#[serde(rename = "lastName")]
pub last_name: String,
}
impl RegisterRequest {
pub fn to_user(self) -> ApiResult<User> {
pub fn to_user(self) -> CoreResult<User> {
let password_hash = hash(&self.password)?;
Ok(User {
id: Uuid::new_v4(),
email: self.email.to_lowercase(),
username: self.username,
email: match self.email {
Some(email) => Some(email.to_lowercase()),
None => None,
},
email_verified: false,
password_hash,
role: USER_ROLE.to_string(),
@@ -41,31 +58,34 @@ impl RegisterRequest {
#[schema(
example = json!(
{
"email": "user@example.com",
"username": "admin",
"password": "changeme"
}
)
)]
pub struct LoginRequest {
pub email: String,
pub username: String,
pub password: String,
}
#[derive(Debug, Serialize, ToSchema)]
pub struct UserResponse {
pub id: Uuid,
pub username: String,
pub role: String,
#[serde(rename = "firstName")]
pub first_name: String,
#[serde(rename = "lastName")]
pub last_name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub avatar: Option<String>,
#[serde(rename = "emailVerified")]
pub email_verified: bool,
}
impl From<User> for UserResponse {
fn from(user: User) -> Self {
UserResponse {
id: user.id,
username: user.username,
email_verified: user.email_verified,
role: user.role,
first_name: user.first_name,
@@ -87,9 +107,7 @@ pub struct UpdateUser {
}
impl UpdateUser {
pub async fn update(&self, id: &Uuid) -> ApiResult<User> {
let pool = db::pool();
pub async fn update(&self, pool: &Pool<Postgres>, username: &str) -> CoreResult<User> {
let mut query_builder: QueryBuilder<Postgres> =
QueryBuilder::new(&format!("UPDATE {} SET ", TABLE_NAME));
@@ -143,8 +161,8 @@ impl UpdateUser {
query_builder.push("updated_at = ");
query_builder.push_bind(Utc::now());
query_builder.push(" WHERE id = ");
query_builder.push_bind(id);
query_builder.push(" WHERE username = ");
query_builder.push_bind(username);
query_builder.push(" RETURNING *");
let query = query_builder.build_query_as::<User>();
@@ -156,8 +174,8 @@ impl UpdateUser {
#[derive(Debug, Serialize, Deserialize, sqlx::FromRow)]
pub struct User {
pub id: Uuid,
pub email: String,
pub username: String,
pub email: Option<String>,
pub email_verified: bool,
pub password_hash: String,
pub role: String,
@@ -169,34 +187,32 @@ pub struct User {
}
impl User {
pub async fn select(id: &Uuid) -> Option<Self> {
let pool = db::pool();
pub async fn select(pool: &Pool<Postgres>, username: &str) -> Option<Self> {
let user: Option<Self> = sqlx::query_as::<_, Self>(&format!(
r#"
SELECT * FROM {} WHERE id = $1
SELECT * FROM {} WHERE username = $1
"#,
TABLE_NAME
))
.bind(id)
.bind(username)
.fetch_optional(pool)
.await
.unwrap_or_else(|err| {
log::error!("Unable to find user by id '{}': {}", id, err);
log::error!("Unable to find user '{}': {}", username, err);
None
});
user
}
pub async fn select_by_email(email: &str) -> Option<Self> {
let pool = db::pool();
pub async fn select_by_email(pool: &Pool<Postgres>, email: &str) -> Option<Self> {
let user: Option<Self> = sqlx::query_as::<_, Self>(&format!(
r#"
SELECT * FROM {} WHERE email = LOWER($1)
SELECT * FROM {} WHERE email = $1
"#,
TABLE_NAME
))
.bind(email)
.bind(email.to_lowercase())
.fetch_optional(pool)
.await
.unwrap_or_else(|err| {
@@ -207,9 +223,8 @@ impl User {
user
}
pub async fn count() -> i64 {
let pool = db::pool();
#[allow(dead_code)]
pub async fn count(pool: &Pool<Postgres>) -> i64 {
sqlx::query_scalar(&format!(
r#"
SELECT COUNT(*) FROM {}
@@ -221,12 +236,11 @@ impl User {
.unwrap_or_else(|_| 0)
}
pub async fn insert(&self) -> ApiResult<User> {
let pool = db::pool();
pub async fn insert(&self, pool: &Pool<Postgres>) -> CoreResult<User> {
let user: User = sqlx::query_as::<_, Self>(&format!(
r#"
INSERT INTO {} (
id,
username,
email,
email_verified,
password_hash,
@@ -242,7 +256,7 @@ impl User {
"#,
TABLE_NAME,
))
.bind(&self.id)
.bind(&self.username)
.bind(&self.email)
.bind(&self.email_verified)
.bind(&self.password_hash)

View File

@@ -0,0 +1,61 @@
use crate::error::CoreResult;
use serde::Deserialize;
use sqlx::{Pool, Postgres};
const TABLE_NAME: &str = "user_airport_favorites";
#[derive(Debug, Deserialize, sqlx::FromRow)]
pub struct UserFavorite {
pub username: String,
pub icao: String,
}
impl UserFavorite {
pub async fn select_all(pool: &Pool<Postgres>, username: &str) -> CoreResult<Vec<String>> {
let user_favorites: Vec<UserFavorite> = sqlx::query_as::<_, UserFavorite>(&format!(
r#"
SELECT * FROM {} WHERE username = $1
"#,
TABLE_NAME
))
.bind(username)
.fetch_all(pool)
.await?;
let favorites = user_favorites.iter().map(|uf| uf.icao.clone()).collect();
Ok(favorites)
}
pub async fn insert(pool: &Pool<Postgres>, username: &str, icao: &str) -> CoreResult<()> {
sqlx::query(&format!(
r#"
INSERT INTO {} (
username, icao
) VALUES ($1, $2)
"#,
TABLE_NAME
))
.bind(username)
.bind(icao)
.execute(pool)
.await?;
Ok(())
}
pub async fn delete(pool: &Pool<Postgres>, username: &str, icao: &str) -> CoreResult<()> {
sqlx::query(&format!(
r#"
DELETE FROM {} WHERE username = $1 AND icao = $2
"#,
TABLE_NAME
))
.bind(username)
.bind(icao)
.execute(pool)
.await?;
Ok(())
}
}

View File

@@ -1,21 +1,11 @@
use argon2::{
Argon2, PasswordHash, PasswordHasher, PasswordVerifier,
password_hash::{SaltString, rand_core::OsRng},
};
use argon2::{Argon2, PasswordHash, PasswordHasher, PasswordVerifier};
use argon2::password_hash::rand_core::OsRng;
use argon2::password_hash::SaltString;
use rand::distr::Alphanumeric;
use rand::prelude::*;
use rand::Rng;
use rand_chacha::ChaCha20Rng;
mod auth;
mod email_token;
mod routes;
mod session;
pub use auth::*;
pub use routes::init_routes;
pub use session::*;
use crate::error::{ApiResult, Error};
use rand_chacha::rand_core::SeedableRng;
use crate::error::CoreResult;
pub fn csprng(take: usize) -> String {
// Generate a CSPRNG 128-bit (16 byte) ID using alphanumeric characters (a-z, A-Z, 0-9)
@@ -27,7 +17,7 @@ pub fn csprng(take: usize) -> String {
.collect()
}
pub fn hash(string: &str) -> ApiResult<String> {
pub fn hash(string: &str) -> CoreResult<String> {
let salt = SaltString::generate(&mut OsRng);
let hash = Argon2::default()
.hash_password(string.as_bytes(), &salt)?
@@ -53,17 +43,6 @@ pub fn verify_hash(string: &str, hashed_string: &str) -> bool {
.is_ok()
}
pub fn verify_role(auth: &Auth, role: &str) -> ApiResult<()> {
if auth.user.role == role {
Ok(())
} else {
Err(Error {
status: 403,
details: "User does not have permission to perform this action.".to_string(),
})
}
}
#[cfg(test)]
mod tests {
use super::*;

View File

@@ -2,17 +2,15 @@ use crate::airports::{
AirportCategory, Communication, CommunicationRow, Runway, RunwayRow, UpdateCommunication,
UpdateRunway,
};
use crate::db;
use crate::error::{ApiResult, Error};
use crate::metars::Metar;
use chrono::{DateTime, Utc};
use futures_util::try_join;
use reqwest::Client;
use serde::{Deserialize, Serialize};
use sqlx::{Postgres, QueryBuilder};
use sqlx::{Pool, Postgres, QueryBuilder};
use std::collections::HashMap;
use std::str::FromStr;
use utoipa::{IntoParams, ToSchema};
use crate::error::{CoreError, CoreErrorKind, CoreResult};
use crate::metars::Metar;
const TABLE_NAME: &str = "airports";
const DEFAULT_COLUMNS: &str = "icao, iata, local, name, category, iso_country, \
@@ -81,6 +79,54 @@ impl Default for AirportQuery {
}
}
// impl AirportQuery {
// pub fn builder() -> AirportQueryBuilder {
// AirportQueryBuilder::new()
// }
// }
// pub struct AirportQueryBuilder {
// inner: AirportQuery,
// }
//
// impl AirportQueryBuilder {
// /// start the builder
// pub fn new() -> Self {
// AirportQueryBuilder {
// inner: AirportQuery::default(),
// }
// }
//
// pub fn page(mut self, page: u32) -> Self {
// self.inner.page = Some(page);
// self
// }
//
// pub fn limit(mut self, limit: u32) -> Self {
// self.inner.limit = Some(limit);
// self
// }
//
// pub fn icaos<T: Into<String>>(mut self, v: T) -> Self {
// self.inner.icaos = Some(v.into());
// self
// }
//
// pub fn iatas<T: Into<String>>(mut self, v: T) -> Self {
// self.inner.iatas = Some(v.into());
// self
// }
//
// pub fn metars(mut self, v: bool) -> Self {
// self.inner.metars = Some(v);
// self
// }
//
// pub fn build(self) -> AirportQuery {
// self.inner
// }
// }
#[derive(Debug, Deserialize, ToSchema)]
pub struct Bounds {
pub north_east_lat: f32,
@@ -90,11 +136,11 @@ pub struct Bounds {
}
impl Bounds {
fn parse(input: &str) -> ApiResult<Bounds> {
fn parse(input: &str) -> CoreResult<Bounds> {
let parts: Vec<&str> = input.split(',').collect();
if parts.len() != 4 {
return Err(Error::new(
400,
return Err(CoreError::new(
CoreErrorKind::InvalidInput,
format!("Expected 4 fields in bounds but received {}", parts.len()),
));
}
@@ -208,22 +254,21 @@ impl From<AirportRow> for Airport {
}
impl Airport {
pub async fn select(client: &Client, icao: &str, metar: bool) -> Option<Self> {
let pool = db::pool();
pub async fn select(pool: &Pool<Postgres>, icao: &str, metar: bool) -> Option<Self> {
let airport_fut = async {
sqlx::query_as(&format!(
"SELECT {} FROM {} WHERE icao = $1",
DEFAULT_COLUMNS, TABLE_NAME
))
.bind(icao)
.bind(icao.to_uppercase())
.fetch_optional(pool)
.await
};
let metar_fut = async {
if metar {
match Metar::find_all_distinct(client, &vec![icao.to_string()]).await {
match Metar::get_all_distinct(pool, &vec![icao.to_uppercase()]).await {
Ok(m) => Some(m.into_iter().nth(0)),
Err(err) => {
log::error!("{}", err);
@@ -235,8 +280,8 @@ impl Airport {
}
};
let runways_fut = Runway::select_all(icao);
let communications_fut = Communication::select_all(icao);
let runways_fut = Runway::select_all(pool, icao);
let communications_fut = Communication::select_all(pool, icao);
let (airport_result, runways_result, communications_result, metar_result) =
tokio::join!(airport_fut, runways_fut, communications_fut, metar_fut);
@@ -286,15 +331,21 @@ impl Airport {
})
}
pub async fn select_all(client: &Client, query: &AirportQuery) -> ApiResult<Vec<Self>> {
let pool = db::pool();
pub async fn select_all(pool: &Pool<Postgres>, query: &AirportQuery) -> CoreResult<Vec<Self>> {
let mut builder =
QueryBuilder::<Postgres>::new(format!("SELECT {} FROM {}", DEFAULT_COLUMNS, TABLE_NAME));
let mut has_where = false;
Self::push_condition_array(&mut builder, &mut has_where, "icao", &query.icaos);
Self::push_condition_array(&mut builder, &mut has_where, "iata", &query.iatas);
let icaos = match &query.icaos {
Some(icaos) => Some(icaos.to_uppercase()),
None => None,
};
Self::push_condition_array(&mut builder, &mut has_where, "icao", &icaos);
let iatas = match &query.iatas {
Some(iatas) => Some(iatas.to_uppercase()),
None => None,
};
Self::push_condition_array(&mut builder, &mut has_where, "iata", &iatas);
Self::push_condition_array(
&mut builder,
&mut has_where,
@@ -313,7 +364,11 @@ impl Airport {
"municipality",
&query.municipalities,
);
Self::push_condition_array(&mut builder, &mut has_where, "local", &query.locals);
let locals = match &query.locals {
Some(locals) => Some(locals.to_uppercase()),
None => None,
};
Self::push_condition_array(&mut builder, &mut has_where, "local", &locals);
Self::push_condition_array(&mut builder, &mut has_where, "category", &query.categories);
Self::push_condition_like(&mut builder, &mut has_where, "name", &query.name);
Self::push_condition_bounds(&mut builder, &mut has_where, &query.bounds)?;
@@ -348,13 +403,13 @@ impl Airport {
return Ok(airports);
}
// Bulk update airport sub-fields
let icaos: Vec<String> = airports.iter().map(|a| a.icao.clone()).collect();
// Bulk update airport subfields
let icaos: Vec<String> = airports.iter().map(|a| a.icao.to_uppercase()).collect();
let runway_future = Runway::select_all_map(icaos.clone());
let frequency_future = Communication::select_all_map(icaos.clone());
let runway_future = Runway::select_all_map(pool, &icaos);
let frequency_future = Communication::select_all_map(pool, &icaos);
let metar_future = if query.metars.unwrap_or(false) {
Some(Metar::find_all_distinct(client, &icaos))
Some(Metar::get_all_distinct(pool, &icaos))
} else {
None
};
@@ -394,9 +449,7 @@ impl Airport {
Ok(airports)
}
pub async fn count(query: &AirportQuery) -> i64 {
let pool = db::pool();
pub async fn count(pool: &Pool<Postgres>, query: &AirportQuery) -> i64 {
let mut builder = QueryBuilder::<Postgres>::new("SELECT COUNT(*) FROM ");
builder.push(TABLE_NAME);
@@ -433,9 +486,7 @@ impl Airport {
sql_query.fetch_one(pool).await.unwrap_or_else(|_| 0)
}
pub async fn insert(&self) -> ApiResult<Self> {
let pool = db::pool();
pub async fn insert(&self, pool: &Pool<Postgres>) -> CoreResult<Self> {
let mut all_runway_rows: Vec<RunwayRow> = Vec::new();
let mut all_frequency_rows: Vec<CommunicationRow> = Vec::new();
for runway in &self.runways {
@@ -444,8 +495,8 @@ impl Airport {
for frequency in &self.communications {
all_frequency_rows.push(Communication::into(frequency, &self.icao));
}
Runway::insert_all(&all_runway_rows).await?;
Communication::insert_all(&all_frequency_rows).await?;
Runway::insert_all(pool, &all_runway_rows).await?;
Communication::insert_all(pool, &all_frequency_rows).await?;
let airport: AirportRow = sqlx::query_as(&format!(
r#"
@@ -483,8 +534,7 @@ impl Airport {
Ok(airport.into())
}
pub async fn insert_all(airports: Vec<Self>) -> ApiResult<()> {
let pool = db::pool();
pub async fn insert_all(pool: &Pool<Postgres>, airports: Vec<Self>) -> CoreResult<()> {
let chunk_size = 1000;
let mut all_runway_rows: Vec<RunwayRow> = Vec::new();
let mut all_frequency_rows: Vec<CommunicationRow> = Vec::new();
@@ -502,11 +552,12 @@ impl Airport {
.collect();
for chunk in airport_rows.chunks(chunk_size) {
let mut query_builder: QueryBuilder<Postgres> = QueryBuilder::new(
"INSERT INTO airports (icao, iata, local, name, category, \
let mut query_builder: QueryBuilder<Postgres> = QueryBuilder::new(format!(
"INSERT INTO {} (icao, iata, local, name, category, \
iso_country, iso_region, municipality, elevation_ft, \
longitude, latitude, geometry, has_tower, has_beacon, public) ",
);
TABLE_NAME
));
query_builder.push_values(chunk, |mut b, row| {
b.push_bind(&row.icao)
.push_bind(&row.iata)
@@ -533,16 +584,14 @@ impl Airport {
query.execute(pool).await?;
}
Runway::insert_all(&all_runway_rows).await?;
Communication::insert_all(&all_frequency_rows).await?;
Runway::insert_all(pool, &all_runway_rows).await?;
Communication::insert_all(pool, &all_frequency_rows).await?;
Ok(())
}
// TODO
pub async fn update(icao: &str, airport: &UpdateAirport) -> ApiResult<()> {
let pool = db::pool();
pub async fn update(pool: &Pool<Postgres>, icao: &str, airport: &UpdateAirport) -> CoreResult<()> {
let mut query_builder: QueryBuilder<Postgres> =
QueryBuilder::new(format!("UPDATE {} SET ", TABLE_NAME));
if let Some(latest_metar_observation) = airport.latest_metar_observation {
@@ -557,9 +606,7 @@ impl Airport {
Ok(())
}
pub async fn delete(icao: &str) -> ApiResult<()> {
let pool = db::pool();
pub async fn delete(pool: &Pool<Postgres>, icao: &str) -> CoreResult<()> {
sqlx::query(&format!(
r#"
DELETE FROM {} WHERE icao = $1
@@ -573,9 +620,7 @@ impl Airport {
Ok(())
}
pub async fn delete_all() -> ApiResult<()> {
let pool = db::pool();
pub async fn delete_all(pool: &Pool<Postgres>) -> CoreResult<()> {
sqlx::query(&format!(
r#"
DELETE FROM {} WHERE true
@@ -642,7 +687,7 @@ impl Airport {
builder: &mut QueryBuilder<'a, Postgres>,
has_where: &mut bool,
field: &'a Option<String>,
) -> ApiResult<()> {
) -> CoreResult<()> {
// Query bounds
if let Some(bounds_string) = field {
if !*has_where {

View File

@@ -1,10 +1,9 @@
use crate::db;
use crate::error::ApiResult;
use serde::{Deserialize, Serialize};
use sqlx::{Postgres, QueryBuilder};
use sqlx::{Pool, Postgres, QueryBuilder};
use std::collections::HashMap;
use utoipa::ToSchema;
use uuid::Uuid;
use crate::error::CoreResult;
const TABLE_NAME: &str = "communications";
@@ -65,9 +64,7 @@ impl Communication {
}
}
pub async fn select_all_map(icaos: Vec<String>) -> ApiResult<HashMap<String, Vec<Self>>> {
let pool = db::pool();
pub async fn select_all_map(pool: &Pool<Postgres>, icaos: &Vec<String>) -> CoreResult<HashMap<String, Vec<Self>>> {
let frequency_rows: Vec<CommunicationRow> = sqlx::query_as(&format!(
r#"SELECT * FROM {} WHERE icao = ANY($1)"#,
TABLE_NAME
@@ -89,9 +86,7 @@ impl Communication {
Ok(frequency_map)
}
pub async fn select_all(icao: &str) -> ApiResult<Vec<Self>> {
let pool = db::pool();
pub async fn select_all(pool: &Pool<Postgres>, icao: &str) -> CoreResult<Vec<Self>> {
let frequency_row: Vec<CommunicationRow> = sqlx::query_as(&format!(
r#"
SELECT * FROM {} WHERE icao = $1
@@ -104,8 +99,7 @@ impl Communication {
Ok(frequency_row.into_iter().map(From::from).collect())
}
pub async fn insert_all(communications: &Vec<CommunicationRow>) -> ApiResult<()> {
let pool = db::pool();
pub async fn insert_all(pool: &Pool<Postgres>, communications: &Vec<CommunicationRow>) -> CoreResult<()> {
let chunk_size = 1000;
for chunk in communications.chunks(chunk_size) {

View File

@@ -1,7 +1,6 @@
use crate::db;
use crate::error::ApiResult;
use crate::error::CoreResult;
use serde::{Deserialize, Serialize};
use sqlx::{Postgres, QueryBuilder};
use sqlx::{Pool, Postgres, QueryBuilder};
use std::collections::HashMap;
use utoipa::ToSchema;
use uuid::Uuid;
@@ -64,9 +63,7 @@ impl Runway {
}
}
pub async fn select_all_map(icaos: Vec<String>) -> ApiResult<HashMap<String, Vec<Self>>> {
let pool = db::pool();
pub async fn select_all_map(pool: &Pool<Postgres>, icaos: &Vec<String>) -> CoreResult<HashMap<String, Vec<Self>>> {
let runway_rows: Vec<RunwayRow> = sqlx::query_as(&format!(
r#"SELECT * FROM {} WHERE icao = ANY($1)"#,
TABLE_NAME
@@ -85,9 +82,7 @@ impl Runway {
Ok(runway_map)
}
pub async fn select_all(icao: &str) -> ApiResult<Vec<Self>> {
let pool = db::pool();
pub async fn select_all(pool: &Pool<Postgres>, icao: &str) -> CoreResult<Vec<Self>> {
let runway_rows: Vec<RunwayRow> = sqlx::query_as(&format!(
r#"
SELECT * FROM {} WHERE icao = $1
@@ -100,8 +95,7 @@ impl Runway {
Ok(runway_rows.into_iter().map(From::from).collect())
}
pub async fn insert_all(runways: &Vec<RunwayRow>) -> ApiResult<()> {
let pool = db::pool();
pub async fn insert_all(pool: &Pool<Postgres>, runways: &Vec<RunwayRow>) -> CoreResult<()> {
let chunk_size = 1000;
for chunk in runways.chunks(chunk_size) {

220
crates/lib/src/error.rs Normal file
View File

@@ -0,0 +1,220 @@
use std::fmt::{Display, Formatter};
use std::sync::{MutexGuard, PoisonError};
use regex::Regex;
use serde::de::StdError;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum CoreErrorKind {
NotFound,
InvalidInput,
Conflict,
Unauthorized,
Forbidden,
PreconditionFailed,
Timeout,
Cancelled,
Unavailable,
Internal,
External,
}
#[derive(Debug)]
pub struct CoreError {
pub kind: CoreErrorKind,
pub message: String,
pub context: Vec<(&'static str, String)>,
source: Option<Box<dyn StdError>>
}
impl CoreError {
pub fn new(kind: CoreErrorKind, message: impl Into<String>) -> Self {
Self {
kind,
message: message.into(),
context: vec![],
source: None,
}
}
pub fn with_source(kind: CoreErrorKind, message: impl Into<String>, source: impl StdError + Send + Sync + 'static) -> Self {
Self {
kind,
message: message.into(),
context: vec![],
source: Some(Box::new(source)),
}
}
pub fn context(mut self, context: Vec<(&'static str, String)>) -> Self {
self.context = context;
self
}
}
impl Display for CoreError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?} - {}", self.kind, self.message)
}
}
impl StdError for CoreError {
fn source(&self) -> Option<&(dyn StdError + 'static)> {
self.source.as_deref()
}
}
pub type CoreResult<T> = Result<T, CoreError>;
pub fn not_found(entity: &'static str, id: impl Into<String>) -> CoreError {
CoreError::new(CoreErrorKind::NotFound, format!("{entity} not found: {}", id.into()))
}
impl From<argon2::password_hash::Error> for CoreError {
fn from(error: argon2::password_hash::Error) -> Self {
Self::new(CoreErrorKind::External, error.to_string())
}
}
impl From<std::io::Error> for CoreError {
fn from(error: std::io::Error) -> Self {
Self::new(CoreErrorKind::External, format!("Unknown IO error: {:?}", error))
}
}
impl From<redis::RedisError> for CoreError {
fn from(error: redis::RedisError) -> Self {
Self::new(CoreErrorKind::External, format!("Unknown redis error: {:?}", error))
}
}
impl From<sqlx::Error> for CoreError {
fn from(error: sqlx::Error) -> Self {
match error {
sqlx::Error::RowNotFound => CoreError::new(CoreErrorKind::NotFound, "Not found".to_string()),
sqlx::Error::ColumnIndexOutOfBounds { .. } => CoreError::new(CoreErrorKind::InvalidInput, error.to_string()),
sqlx::Error::ColumnNotFound { .. } => CoreError::new(CoreErrorKind::NotFound, error.to_string()),
sqlx::Error::ColumnDecode { .. } => CoreError::new(CoreErrorKind::External, error.to_string()),
sqlx::Error::Decode(_) => CoreError::new(CoreErrorKind::External, error.to_string()),
sqlx::Error::PoolTimedOut => CoreError::new(CoreErrorKind::External, error.to_string()),
sqlx::Error::PoolClosed => CoreError::new(CoreErrorKind::External, error.to_string()),
sqlx::Error::Tls(_) => CoreError::new(CoreErrorKind::External, error.to_string()),
sqlx::Error::Io(_) => CoreError::new(CoreErrorKind::External, error.to_string()),
sqlx::Error::Protocol(_) => CoreError::new(CoreErrorKind::External, error.to_string()),
sqlx::Error::Configuration(_) => CoreError::new(CoreErrorKind::External, error.to_string()),
sqlx::Error::AnyDriverError(_) => CoreError::new(CoreErrorKind::External, error.to_string()),
sqlx::Error::Database(err) => {
if let Some(code) = err.code() {
match code.trim() {
// Unique violation
"23505" => return CoreError::new(CoreErrorKind::External, err.to_string()),
_ => (),
}
}
CoreError::new(CoreErrorKind::External, err.to_string())
}
sqlx::Error::Migrate(_) => CoreError::new(CoreErrorKind::External, error.to_string()),
sqlx::Error::TypeNotFound { type_name } => {
CoreError::new(CoreErrorKind::External, format!("Type not found: {}", type_name))
}
sqlx::Error::WorkerCrashed => CoreError::new(CoreErrorKind::External, error.to_string()),
_ => CoreError::new(CoreErrorKind::External, error.to_string()),
}
}
}
impl From<reqwest::Error> for CoreError {
fn from(error: reqwest::Error) -> Self {
match error.status() {
Some(status_code) => {
if status_code.is_client_error() {
Self::new(CoreErrorKind::External, format!("Client reqwest error: {:?}", error))
} else if status_code.is_server_error() {
Self::new(CoreErrorKind::External, format!("Server reqwest error: {:?}", error))
} else {
Self::new(CoreErrorKind::External, format!("Unknown reqwest error: {:?}", error))
}
}
_ => Self::new(CoreErrorKind::External, format!("Unknown reqwest error: {:?}", error)),
}
}
}
impl From<s3::error::S3Error> for CoreError {
fn from(error: s3::error::S3Error) -> Self {
match error {
s3::error::S3Error::Credentials(err) => {
Self::new(CoreErrorKind::External, format!("Unknown s3 credentials error: {:?}", err))
}
s3::error::S3Error::FromUtf8(err) => {
Self::new(CoreErrorKind::External, format!("Unknown s3 from utf8 error: {:?}", err))
}
s3::error::S3Error::FmtError(err) => {
Self::new(CoreErrorKind::External, format!("Unknown s3 fmt error: {:?}", err))
}
s3::error::S3Error::HmacInvalidLength(err) => Self::new(
CoreErrorKind::External,
format!("Unknown s3 hmac invalid length error: {:?}", err),
),
_ => {
let re = Regex::new(r"HTTP (\d{3})").unwrap();
// Apply the regex to the input string
if let Some(captures) = re.captures(&error.to_string()) {
if let Some(http_code_str) = captures.get(1) {
if let Ok(http_code) = http_code_str.as_str().parse::<u16>() {
return Self::new(CoreErrorKind::External, error.to_string()).context(vec![("http_code", http_code.to_string())]);
}
}
}
Self::new(CoreErrorKind::External, format!("Unknown s3 error: {:?}", error))
}
}
}
}
impl From<std::env::VarError> for CoreError {
fn from(error: std::env::VarError) -> Self {
Self::new(
CoreErrorKind::External,
format!("Unknown environment variable error: {:?}", error),
)
}
}
impl From<serde_json::Error> for CoreError {
fn from(error: serde_json::Error) -> Self {
Self::new(CoreErrorKind::External, format!("Unknown serde_json error: {:?}", error))
}
}
impl<'a, T> From<PoisonError<MutexGuard<'a, T>>> for CoreError {
fn from(_: PoisonError<MutexGuard<'a, T>>) -> Self {
Self::new(CoreErrorKind::External, "Failed to acquire lock".to_string())
}
}
impl From<core::num::ParseIntError> for CoreError {
fn from(error: core::num::ParseIntError) -> Self {
Self::new(CoreErrorKind::External, format!("Integer parse error: {:?}", error))
}
}
impl From<core::num::ParseFloatError> for CoreError {
fn from(error: core::num::ParseFloatError) -> Self {
Self::new(CoreErrorKind::External, format!("Float parse error: {:?}", error))
}
}
impl From<regex::Error> for CoreError {
fn from(error: regex::Error) -> Self {
Self::new(CoreErrorKind::External, error.to_string())
}
}
impl From<chrono::ParseError> for CoreError {
fn from(error: chrono::ParseError) -> Self {
Self::new(CoreErrorKind::External, format!("Chrono parse error: {:?}", error))
}
}

View File

@@ -0,0 +1,92 @@
use crate::error::{CoreResult, CoreError, CoreErrorKind};
use governor::clock::DefaultClock;
use governor::state::{InMemoryState, NotKeyed};
use governor::{Quota, RateLimiter};
use reqwest::header::{IF_NONE_MATCH, RETRY_AFTER};
use reqwest::{Certificate, Client, Response, StatusCode};
use std::env;
use std::num::NonZeroU32;
use std::sync::Arc;
use std::time::Duration;
use tokio::time::sleep;
#[derive(Debug, Clone)]
pub struct HttpClient {
client: Client,
limiter: Arc<RateLimiter<NotKeyed, InMemoryState, DefaultClock>>,
pub default_retry_after: u64,
}
impl HttpClient {
pub fn new(default_retry_after: u64) -> CoreResult<Self> {
let mut client_builder = Client::builder()
.timeout(Duration::from_secs(10))
.tls_built_in_root_certs(true);
if let Ok(val) = env::var("NGINX_SSL_ENABLED") {
if val == "true" {
let certificate_path = env::var("SSL_CA_PATH")?;
let certificate_data = std::fs::read(certificate_path)?;
let certificate = Certificate::from_pem(&certificate_data)?;
client_builder = client_builder.add_root_certificate(certificate);
}
}
let client = client_builder.build()?;
let quota = Quota::per_second(NonZeroU32::new(15).unwrap());
let limiter = RateLimiter::direct(quota);
let limiter = Arc::new(limiter);
Ok(Self {
client,
limiter,
default_retry_after,
})
}
pub fn default() -> CoreResult<Self> {
Self::new(60)
}
pub async fn get(&self, url: &str, etag: Option<String>) -> CoreResult<Response> {
self.limiter.until_ready().await;
let mut request = self.client.get(url);
if let Some(ref etag) = etag {
request = request.header(IF_NONE_MATCH, etag);
}
let mut response = request.send().await?;
// Handle too many requests
if response.status() == StatusCode::TOO_MANY_REQUESTS {
let retry_after = response
.headers()
.get(RETRY_AFTER)
.and_then(|hdr| hdr.to_str().ok())
.and_then(|s| s.parse::<u64>().ok())
.unwrap_or(self.default_retry_after);
log::warn!(
"Received 429 Too Many Requests, retrying after {}s",
retry_after
);
sleep(Duration::from_secs(retry_after)).await;
// Retry once more
response = self.client.get(url).send().await?;
} else if response.status() == StatusCode::NOT_MODIFIED {
log::warn!("Received 304 Not modified")
}
if response.status() != 200 {
return Err(CoreError::new(
CoreErrorKind::External,
format!("Request returned status {}", response.status()),
));
}
Ok(response)
}
}

6
crates/lib/src/lib.rs Normal file
View File

@@ -0,0 +1,6 @@
pub mod accounts;
pub mod airports;
pub mod metars;
pub mod http_client;
pub mod state;
pub mod error;

View File

@@ -1,9 +1,8 @@
use crate::db::redis_async_connection;
use crate::error::ApiResult;
use crate::metars::Metar;
use chrono::{DateTime, Utc};
use redis::{AsyncCommands, RedisResult};
use serde::{Deserialize, Serialize};
use crate::error::CoreResult;
use crate::metars::model::Metar;
use crate::state::AppState;
#[derive(Debug, Serialize, Deserialize)]
pub struct MetarCheck {
@@ -14,8 +13,8 @@ pub struct MetarCheck {
}
impl MetarCheck {
pub async fn new(icao: String, status: bool) -> Self {
match Self::get(&icao).await {
pub async fn new(state: &AppState, icao: String, status: bool) -> Self {
match Self::get(state, &icao).await {
Some(c) => Self {
icao,
status,
@@ -31,37 +30,27 @@ impl MetarCheck {
}
}
pub async fn get(icao: &str) -> Option<MetarCheck> {
let mut conn = match redis_async_connection().await {
Ok(conn) => conn,
Err(err) => {
log::error!("{}", err);
return None;
}
};
let result: RedisResult<Option<String>> = conn.get(icao).await;
pub async fn get(state: &AppState, icao: &str) -> Option<MetarCheck> {
let result: CoreResult<Option<String>> = state.get(icao).await;
match result {
Ok(Some(value)) => match serde_json::from_str(&value) {
Ok(result) => Some(result),
Err(err) => {
log::error!("{}", err);
log::error!("Unable to get MetarCheck for ICAO {}: {}", icao, err);
None
}
},
Ok(None) => None,
Err(err) => {
log::error!("{}", err);
log::error!("Error getting MetarCheck for ICAO {}: {}", icao, err);
None
}
}
}
pub async fn insert(&self, seconds: u64) -> ApiResult<()> {
let mut conn = redis_async_connection().await?;
pub async fn insert(&self, state: &AppState) -> CoreResult<()> {
let value = serde_json::to_string(&self)?;
conn
.set_ex::<_, _, ()>(self.icao.as_str(), value, seconds)
.await?;
state.set(self.icao.as_str(), &value).await?;
Ok(())
}

View File

@@ -1,7 +1,7 @@
mod metar_check;
mod model;
mod routes;
mod utils;
pub use metar_check::*;
pub use model::*;
pub use routes::init_routes;
pub use utils::*;

View File

@@ -1,19 +1,35 @@
use crate::airports::{Airport, UpdateAirport};
use crate::db::redis_async_connection;
use crate::error::Error;
use crate::metars::MetarCheck;
use crate::{db, error::ApiResult};
use chrono::{DateTime, Datelike, NaiveDate, Utc};
use redis::{AsyncCommands, RedisResult};
use reqwest::Client;
use crate::error::{CoreError, CoreErrorKind, CoreResult};
use crate::metars::utils::parse_metar_time;
use chrono::{DateTime, Utc};
use flate2::read::GzDecoder;
use reqwest::header::ETAG;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use sqlx::{Pool, Postgres, QueryBuilder};
use std::collections::HashSet;
use std::env;
use std::fmt::Display;
use std::io::{Cursor, Read};
use std::str::FromStr;
use std::sync::OnceLock;
use regex::Regex;
use utoipa::ToSchema;
use crate::metars::metar_check::MetarCheck;
use crate::state::AppState;
static TIME_OFFSET: OnceLock<i64> = OnceLock::new();
const TABLE_NAME: &str = "metars";
const DEFAULT_REFRESH_DURATION: i64 = 3000;
fn time_offset() -> i64 {
*TIME_OFFSET.get_or_init(|| {
env::var("API_METAR_TIME_OFFSET")
.unwrap_or("1800".to_string())
.parse::<i64>()
.unwrap_or(1800)
})
}
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct Metar {
@@ -70,12 +86,12 @@ pub enum ReportModifier {
}
impl FromStr for ReportModifier {
type Err = Error;
type Err = CoreError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"AUTO" => Ok(ReportModifier::Auto),
"COR" => Ok(ReportModifier::Corrected),
_ => Err(Error::new(400, format!("Invalid report modifier '{}'", s))),
_ => Err(CoreError::new(CoreErrorKind::InvalidInput, format!("Invalid report modifier '{}'", s))),
}
}
}
@@ -120,13 +136,13 @@ pub enum AutomatedStationType {
}
impl FromStr for AutomatedStationType {
type Err = Error;
type Err = CoreError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"AO1" => Ok(AutomatedStationType::WithoutPrecipitationDiscriminator),
"AO2" => Ok(AutomatedStationType::WithPrecipitationDiscriminator),
_ => Err(Error::new(
400,
_ => Err(CoreError::new(
CoreErrorKind::InvalidInput,
format!("Invalid automated station type '{}'", s),
)),
}
@@ -262,8 +278,7 @@ struct MetarRow {
}
impl MetarRow {
async fn insert(&self) -> ApiResult<()> {
let pool = db::pool();
async fn insert(&self, pool: &Pool<Postgres>) -> CoreResult<()> {
sqlx::query(&format!(
r#"
INSERT INTO {} (
@@ -288,13 +303,47 @@ impl MetarRow {
Ok(())
}
async fn insert_all(pool: &Pool<Postgres>, metars: Vec<Metar>) -> CoreResult<()> {
let chunk_size = 1000;
for chunk in metars.chunks(chunk_size) {
let mut query_builder: QueryBuilder<Postgres> = QueryBuilder::new(format!(
"INSERT INTO {} (icao, observation_time, raw_text, data) ",
TABLE_NAME
));
query_builder.push_values(chunk, |mut b, metar| {
let row: Self = match metar.to_row() {
Ok(row) => row,
Err(e) => {
log::warn!("Failed to serialize METAR data: {}", e);
return;
}
};
b.push_bind(row.icao)
.push_bind(row.observation_time)
.push_bind(row.raw_text)
.push_bind(row.data);
});
query_builder.push(
" ON CONFLICT (icao, observation_time) DO UPDATE SET \
raw_text = EXCLUDED.raw_text, \
data = EXCLUDED.data",
);
let query = query_builder.build();
query.execute(pool).await?;
}
Ok(())
}
}
impl Metar {
fn parse_multiple(metar_strings: &Vec<&str>) -> ApiResult<Vec<Self>> {
let mut metars: Vec<Metar> = vec![];
fn parse_multiple(pool: &Pool<Postgres>, metar_strings: &Vec<&str>) -> CoreResult<Vec<Self>> {
let mut metars: Vec<Self> = vec![];
for metar_string in metar_strings {
match Metar::parse(metar_string) {
match Self::parse(pool, metar_string) {
Ok(metar) => metars.push(metar),
Err(e) => {
log::warn!("Failed to parse metar string: {}", e);
@@ -306,21 +355,26 @@ impl Metar {
Ok(metars)
}
fn parse(metar_string: &str) -> ApiResult<Self> {
fn parse(pool: &Pool<Postgres>, metar_string: &str) -> CoreResult<Self> {
if metar_string.is_empty() {
return Err(Error::new(
404,
return Err(CoreError::new(
CoreErrorKind::InvalidInput,
"Unable to parse empty METAR data".to_string(),
));
}
let metar_string = metar_string
.trim()
.trim_matches(|c| c == '"' || c == '\'' || c == '“' || c == '”' || c == '' || c == '')
.trim();
log::trace!("Parsing METAR data: {}", metar_string);
let mut metar: Metar = Metar::default();
let mut metar: Self = Self::default();
metar.raw_text = metar_string.to_owned();
let mut metar_parts: Vec<&str> = metar_string.split_whitespace().collect();
if metar_parts.len() < 4 {
return Err(Error::new(
500,
return Err(CoreError::new(
CoreErrorKind::InvalidInput,
format!(
"Unable to parse METAR data in an unexpected format: {}",
metar_string
@@ -328,9 +382,16 @@ impl Metar {
));
}
// Remove METAR at start of text
if metar_parts[0].to_string() == "METAR".to_string() {
// Remove METAR at the start of the text
let metar_re: Regex = Regex::new(r"(?i)^[\p{P}\s]*METAR[\p{P}\s]*$")?;
let speci_re: Regex = Regex::new(r"(?i)^[\p{P}\s]*SPECI[\p{P}\s]*$")?;
let token = metar_parts[0].trim();
if metar_re.is_match(token) {
metar_parts.remove(0);
} else if speci_re.is_match(token) {
// TODO: Handle SPECI data
return Err(CoreError::new(CoreErrorKind::InvalidInput, format!("Unable to parse SPECI data: {}", metar_string)));
}
// Station Identifier
@@ -340,11 +401,23 @@ impl Metar {
// Date/Time
let observation_time = metar_parts[0];
metar_parts.remove(0);
let observation_time = Self::parse_time(observation_time)?;
match parse_metar_time(observation_time) {
Ok(observation_time) => {
metar.observation_time = match chrono::DateTime::parse_from_rfc3339(&observation_time) {
Ok(datetime) => datetime.with_timezone(&Utc),
Err(err) => return Err(err.into()),
};
}
Err(err) => {
return Err(CoreError::new(
CoreErrorKind::InvalidInput,
format!(
"Unexpected observation time field '{}': {}; {}",
observation_time, metar_string, err
),
));
}
};
loop {
if metar_parts.is_empty() {
@@ -361,9 +434,8 @@ impl Metar {
}
// Wind Direction and Speed
let wind_re = regex::Regex::new(r"^(?:[0-9]{3}|VRB)[0-9]{2}(?:KT|MPS)$").unwrap();
let wind_gust_re =
regex::Regex::new(r"^(?:[0-9]{3}|VRB)[0-9]{2}G[0-9]{2}(?:KT|MPS)$").unwrap();
let wind_re = regex::Regex::new(r"^(?:[0-9]{3}|VRB)[0-9]{2}(?:KT|MPS)$")?;
let wind_gust_re = regex::Regex::new(r"^(?:[0-9]{3}|VRB)[0-9]{2}G[0-9]{2}(?:KT|MPS)$")?;
// Handle input error where there is a space between the numbers and units
let mut value: Option<String> = None;
if metar_parts.len() >= 2
@@ -397,9 +469,9 @@ impl Metar {
let mut wind_speed_kt = wind[3..5].to_string();
// Convert m/s to kt
if wind.len() == 8 {
wind_speed_kt = (wind_speed_kt.parse::<f64>().unwrap() * 1.94384).to_string();
wind_speed_kt = (wind_speed_kt.parse::<f64>()? * 1.94384).to_string();
}
metar.wind_speed_kt = Some(wind_speed_kt.parse::<f64>().unwrap());
metar.wind_speed_kt = Some(wind_speed_kt.parse::<f64>()?);
} else if wind_gust_re.is_match(&wind) {
let wind_dir_degrees = &wind[0..3];
metar.wind_dir_degrees = Some(wind_dir_degrees.to_string());
@@ -407,26 +479,26 @@ impl Metar {
let mut wind_gust_kt = wind[6..8].to_string();
// Convert m/s to kt
if wind.len() == 9 {
wind_speed_kt = (wind_speed_kt.parse::<f64>().unwrap() * 1.94384).to_string();
wind_gust_kt = (wind_gust_kt.parse::<f64>().unwrap() * 1.94384).to_string();
wind_speed_kt = (wind_speed_kt.parse::<f64>()? * 1.94384).to_string();
wind_gust_kt = (wind_gust_kt.parse::<f64>()? * 1.94384).to_string();
}
metar.wind_speed_kt = Some(wind_speed_kt.parse::<f64>().unwrap());
metar.wind_gust_kt = Some(wind_gust_kt.parse::<f64>().unwrap());
metar.wind_speed_kt = Some(wind_speed_kt.parse::<f64>()?);
metar.wind_gust_kt = Some(wind_gust_kt.parse::<f64>()?);
}
}
None => {}
}
// Variable Wind Direction
let variable_wind_re = regex::Regex::new(r"^[0-9]{3}V[0-9]{3}$").unwrap();
let variable_wind_re = regex::Regex::new(r"^[0-9]{3}V[0-9]{3}$")?;
if !metar_parts.is_empty() && variable_wind_re.is_match(metar_parts[0]) {
metar.variable_wind_dir_degrees = Some(metar_parts[0].to_string());
metar_parts.remove(0);
}
// Visibility
let visibility_re = regex::Regex::new(r"^M?(?:[0-9]+|[0-9]+/[0-9]+)SM$").unwrap();
let visibility_re_m = regex::Regex::new(r"^[0-9]{4}(:?N|NE|NW|S|SE|SW)?$").unwrap();
let visibility_re = regex::Regex::new(r"^M?(?:[0-9]+|[0-9]+/[0-9]+)SM$")?;
let visibility_re_m = regex::Regex::new(r"^[0-9]{4}(:?N|NE|NW|S|SE|SW)?$")?;
if !metar_parts.is_empty() && visibility_re.is_match(metar_parts[0]) {
let visibility_str = &metar_parts[0][0..metar_parts[0].len() - 2];
metar_parts.remove(0);
@@ -460,9 +532,30 @@ impl Metar {
metar_parts.remove(0);
let visibility_parts: Vec<&str> = metar_parts[0].split("/").collect();
metar_parts.remove(0);
if visibility_parts.len() == 1 {
metar.visibility_statute_mi = Some(visibility_parts[0].to_string());
} else if visibility_parts.len() == 2 {
let visibility_left = visibility_parts[0];
let visibility_right =
visibility_parts[1][0..visibility_parts[1].len() - 2].parse::<f64>()?;
// Parse the right-hand of visibility, with or without an SM suffix
let visibility_right_string = match visibility_parts[1].strip_suffix("SM") {
Some(s) => s,
None => {
if visibility_parts[1]
.chars()
.all(|c| c.is_numeric() || c == '.')
{
visibility_parts[1]
} else {
log::warn!(
"Skipping unexpected visibility field '{:?}' ({})",
visibility_parts,
metar_string
);
continue;
}
}
};
let visibility_right = visibility_right_string.parse::<f64>()?;
let visibility = if visibility_left.starts_with("M") {
format!(
"M{}",
@@ -492,12 +585,19 @@ impl Metar {
let visibility = visibility[0..4].parse::<f64>()? * 0.000621371;
metar.visibility_statute_mi = Some(format!("{:.2}", visibility));
}
} else {
log::warn!(
"Skipping unexpected visibility field '{}' ({})",
metar_parts[0],
metar_string
);
}
}
// Runway Visual Range
let rvr_re = regex::Regex::new(r"^R[0-9]{1,3}(?:L|R|C)?/[PM]?[0-9]{4}FT$").unwrap();
let rvr_re = regex::Regex::new(r"^R[0-9]{1,3}(?:L|R|C)?/[PM]?[0-9]{4}FT$")?;
let variable_rvr_re =
regex::Regex::new(r"^R[0-9]{1,3}(?:L|R|C)?/[PM]?[0-9]{4}V[PM]?[0-9]{4}FT$").unwrap();
regex::Regex::new(r"^R[0-9]{1,3}(?:L|R|C)?/[PM]?[0-9]{4}V[PM]?[0-9]{4}FT$")?;
while !metar_parts.is_empty()
&& (rvr_re.is_match(metar_parts[0]) || variable_rvr_re.is_match(metar_parts[0]))
{
@@ -538,58 +638,10 @@ impl Metar {
metar_parts.remove(0);
}
// Sky Condition
if !metar_parts.is_empty() && metar_parts[0] == "CAVOK" {
metar.sky_condition.push(SkyCondition {
sky_cover: "CLR".to_string(),
cloud_base_ft_agl: None,
significant_convective_clouds: None,
});
metar_parts.remove(0);
}
let sky_condition_re =
regex::Regex::new(r"^(?:CLR|SKC|NSC|NCD|(?:FEW|SCT|BKN|OVC|VV)([0-9/]{3})?(?:CB|TCU)?)$")
.unwrap();
while !metar_parts.is_empty() && sky_condition_re.is_match(metar_parts[0]) {
let sky_condition_string = metar_parts[0];
metar_parts.remove(0);
let mut sky_condition = SkyCondition::default();
let mut vv_offset = 0;
if &sky_condition_string[0..2] == "VV" {
sky_condition.sky_cover = "VV".to_string();
vv_offset = 1;
} else {
sky_condition.sky_cover = sky_condition_string[0..3].to_string();
}
if sky_condition_string.len() > 3 - vv_offset {
// Parse out the next three digits
let cloud_base_ft_agl = &sky_condition_string[3 - vv_offset..6 - vv_offset];
if cloud_base_ft_agl == "///" {
sky_condition.cloud_base_ft_agl = None;
} else {
sky_condition.cloud_base_ft_agl = match cloud_base_ft_agl.parse::<i32>() {
Ok(c) => Some(c * 100),
Err(err) => {
log::warn!(
"Unable to parse cloud base in {}: {}",
sky_condition_string,
err
);
None
}
};
}
if sky_condition_string.len() > 6 - vv_offset {
// Parse out the next two digits
let scc = &sky_condition_string[6 - vv_offset..8 - vv_offset];
sky_condition.significant_convective_clouds = Some(scc.to_string());
}
}
metar.sky_condition.push(sky_condition);
}
metar.parse_sky_condition(&mut metar_parts);
// Temperature and Dewpoint
let temp_re = regex::Regex::new(r"^(?:M?[0-9]{2})?/(?:M?[0-9]{2})?$").unwrap();
let temp_re = regex::Regex::new(r"^(?:M?[0-9]{2})?/(?:M?[0-9]{2})?$")?;
if !metar_parts.is_empty() && temp_re.is_match(metar_parts[0]) {
let temp_string = metar_parts[0];
metar_parts.remove(0);
@@ -631,7 +683,7 @@ impl Metar {
}
// Altimeter
let altim_re = regex::Regex::new(r"^A[0-9]{4}$").unwrap();
let altim_re = regex::Regex::new(r"^A[0-9]{4}$")?;
if !metar_parts.is_empty() && altim_re.is_match(metar_parts[0]) {
let altim = metar_parts[0];
metar_parts.remove(0);
@@ -639,7 +691,7 @@ impl Metar {
}
// Pressure
let pressure_re = regex::Regex::new(r"^Q[0-9]{4}$").unwrap();
let pressure_re = regex::Regex::new(r"^Q[0-9]{4}$")?;
if !metar_parts.is_empty() && pressure_re.is_match(metar_parts[0]) {
let pressure = metar_parts[0];
metar_parts.remove(0);
@@ -671,8 +723,8 @@ impl Metar {
if metar_parts.is_empty() {
break;
}
let slp_re = regex::Regex::new(r"^SLP([0-9]{3})$").unwrap();
let hourly_temp_re = regex::Regex::new(r"^T[01][0-9]{3}[01][0-9]{3}$").unwrap();
let slp_re = Regex::new(r"^SLP([0-9]{3})$")?;
let hourly_temp_re = Regex::new(r"^T[01][0-9]{3}[01][0-9]{3}$")?;
let remark = metar_parts[0];
metar_parts.remove(0);
if remark == "AO1" || remark == "AO2" {
@@ -706,8 +758,8 @@ impl Metar {
minutes,
});
} else {
return Err(Error::new(
500,
return Err(CoreError::new(
CoreErrorKind::InvalidInput,
"Input string format is invalid".to_string(),
));
}
@@ -767,7 +819,7 @@ impl Metar {
// Skip unexpected fields
if !metar_parts.is_empty() {
log::warn!(
log::trace!(
"Skipping unexpected field: '{}' ({})",
metar_parts[0],
metar_string
@@ -838,8 +890,10 @@ impl Metar {
// Update the airport's metar observation time
let icao = metar.icao.clone();
let observation_time = metar.observation_time.clone();
let pool = pool.clone();
tokio::spawn(async move {
match Airport::update(
&pool.clone(),
&icao,
&UpdateAirport {
icao: None,
@@ -875,103 +929,139 @@ impl Metar {
Ok(metar)
}
fn parse_time(observation_time: &str) -> ApiResult<String> {
if observation_time.len() != 7 {
return Err(Error::new(
500,
format!("Unable to parse observation time in {}", observation_time),
));
fn parse_sky_condition(&mut self, metar_parts: &mut Vec<&str>) {
// Check if sky condition is CAVOK
if !metar_parts.is_empty() && metar_parts[0] == "CAVOK" {
self.sky_condition.push(SkyCondition {
sky_cover: "CLR".to_string(),
cloud_base_ft_agl: None,
significant_convective_clouds: None,
});
metar_parts.remove(0);
}
let observation_day = match observation_time[0..2].parse::<u32>() {
Ok(day) => day,
Err(err) => return Err(err.into()),
};
let observation_hour = match observation_time[2..4].parse::<u32>() {
Ok(hour) => hour,
Err(err) => return Err(err.into()),
};
let observation_minute = match observation_time[4..6].parse::<u32>() {
Ok(minute) => minute,
Err(err) => return Err(err.into()),
};
let current_time = Utc::now().naive_utc();
let current_year = current_time.year();
let current_month = current_time.month();
let candidate_date = NaiveDate::from_ymd_opt(current_year, current_month, observation_day)
.ok_or_else(|| {
Error::new(
500,
format!(
"Invalid date with day {} for current month",
observation_day
),
let sky_condition_re = regex::Regex::new(
r"^(?:CLR|SKC|NSC|NCD|(?:FEW|SCT|BKN|OVC|VV)([0-9/]{3})?(?:CB|TCU)?)(?:///)?$",
)
})?
.and_hms_opt(observation_hour, observation_minute, 0)
.unwrap();
let obs_datetime = if candidate_date > current_time {
// Subtract one month. (Handle year rollover carefully.)
let (month, year) = if current_month == 1 {
(12, current_year - 1)
} else {
(current_month - 1, current_year)
};
while !metar_parts.is_empty() && sky_condition_re.is_match(metar_parts[0]) {
// Get the next METAR part
let mut sky_condition_string = metar_parts[0];
metar_parts.remove(0);
let adjusted_date =
NaiveDate::from_ymd_opt(year, month, observation_day).ok_or_else(|| {
Error::new(
500,
format!(
"Invalid date with day {} for month {}",
observation_day, month
),
)
})?;
adjusted_date.and_hms(observation_hour, observation_minute, 0)
} else {
candidate_date
};
Ok(obs_datetime.format("%Y-%m-%dT%H:%M:00Z").to_string())
// Remove trailing slashes
if sky_condition_string.ends_with("///") {
sky_condition_string = &sky_condition_string[..sky_condition_string.len() - 3];
}
async fn get_remote_metars(client: &Client, icaos: &Vec<String>) -> ApiResult<Vec<Metar>> {
let mut sky_condition = SkyCondition::default();
// Handle sky cover and optionally vertical visibility
let mut vv_offset = 0;
if &sky_condition_string[0..2] == "VV" {
sky_condition.sky_cover = "VV".to_string();
vv_offset = 1;
} else {
sky_condition.sky_cover = sky_condition_string[0..3].to_string();
}
if sky_condition_string.len() > 3 - vv_offset {
if sky_condition_string.len() < 6 - vv_offset {
// Parse out the significant convective clouds
let scc = &sky_condition_string[3 - vv_offset..];
sky_condition.significant_convective_clouds = Some(scc.to_string());
} else {
// Parse out the next three digits
let cloud_base_ft_agl = &sky_condition_string[3 - vv_offset..6 - vv_offset];
sky_condition.cloud_base_ft_agl = match cloud_base_ft_agl.parse::<i32>() {
Ok(c) => Some(c * 100),
Err(err) => {
log::warn!(
"Unable to parse cloud base in {}: {}",
sky_condition_string,
err
);
None
}
};
// Parse out the significant convective clouds
let scc = &sky_condition_string[6 - vv_offset..];
sky_condition.significant_convective_clouds = Some(scc.to_string());
}
}
self.sky_condition.push(sky_condition);
}
}
pub async fn get_cached_remote_metars(
state: &AppState,
etag: Option<String>,
) -> CoreResult<(Vec<Self>, String)> {
let base_url = env::var("AVIATION_WEATHER_URL").expect("AVIATION_WEATHER_URL must be set");
let url = format!("{}/data/cache/metars.cache.csv.gz", base_url);
let response = state.client.get(&url, etag.clone()).await?;
let new_etag = response
.headers()
.get(ETAG)
.and_then(|h| h.to_str().ok())
.map(|s| s.to_string());
let bytes = response.bytes().await?;
let mut gz = GzDecoder::new(Cursor::new(bytes));
let mut text = String::new();
gz.read_to_string(&mut text)?;
let mut output: Vec<Metar> = Vec::new();
for line in text.lines() {
// Split off the first column
let raw_text = line.splitn(2, ',').next().unwrap();
match Metar::parse(&state.pool, raw_text) {
Ok(m) => output.push(m),
Err(err) => {
log::warn!("{}", err);
}
};
}
match new_etag {
Some(etag) => Ok((output, etag)),
None => match etag {
Some(etag) => Ok((output, etag.to_string())),
None => Ok((output, String::new())),
},
}
}
pub async fn get_remote_metars(state: &AppState, icaos: &Vec<String>) -> CoreResult<Vec<Self>> {
let base_url = env::var("AVIATION_WEATHER_URL").expect("AVIATION_WEATHER_URL must be set");
// Query the remote API for the missing METAR data 10 at a time
let icao_chunks = icaos
.chunks(10)
.map(|chunk| chunk.join(","))
.collect::<Vec<String>>();
let mut metars: Vec<Metar> = vec![];
let mut metars: Vec<Self> = vec![];
for icao_chunk in icao_chunks {
let url = format!(
"{}/metar?ids={}&hours=0&order=id,-obs",
"{}/api/data/metar?ids={}&hours=0&order=id,-obs",
base_url, icao_chunk
);
let mut m = match client.get(url).send().await {
Ok(r) => {
// Check if the status code is 200
if r.status() != 200 {
return Err(Error::new(
500,
format!("Request returned status {}", r.status()),
));
}
match r.text().await {
let mut m = match state.client.get(&url, None).await {
Ok(r) => match r.text().await {
Ok(r) => {
let metar_chunk = r
.trim()
.split("\n")
.filter(|m| !m.trim().is_empty())
.collect();
match Self::parse_multiple(&metar_chunk) {
match Self::parse_multiple(&state.pool, &metar_chunk) {
Ok(m) => m,
Err(err) => return Err(err),
}
}
Err(err) => return Err(Error::new(500, format!("METAR parse failed: {}", err))),
}
}
Err(err) => return Err(CoreError::new(CoreErrorKind::InvalidInput, format!("METAR parse failed: {}", err))),
},
Err(err) => return Err(err.into()),
};
metars.append(&mut m);
@@ -979,27 +1069,26 @@ impl Metar {
Ok(metars)
}
fn from_db(metar_db: MetarRow) -> ApiResult<Metar> {
let metar: Metar = serde_json::from_value(metar_db.data)?;
fn from_row(row: MetarRow) -> CoreResult<Self> {
let metar: Self = serde_json::from_value(row.data)?;
Ok(metar)
}
fn to_db(&self) -> ApiResult<MetarRow> {
fn to_row(&self) -> CoreResult<MetarRow> {
let data = serde_json::to_value(self)?;
Ok(MetarRow {
icao: self.icao.clone(),
icao: self.icao.to_uppercase(),
observation_time: self.observation_time,
raw_text: self.raw_text.clone(),
data,
})
}
pub async fn find_all_distinct(client: &Client, icao_list: &Vec<String>) -> ApiResult<Vec<Self>> {
pub async fn get_all_distinct(pool: &Pool<Postgres>, icao_list: &Vec<String>) -> CoreResult<Vec<Self>> {
if icao_list.is_empty() {
return Ok(Vec::new());
}
let pool = db::pool();
let metar_rows: Vec<MetarRow> = sqlx::query_as::<_, MetarRow>(&format!(
r#"
SELECT DISTINCT ON (icao) * FROM {}
@@ -1011,61 +1100,67 @@ impl Metar {
.bind(icao_list)
.fetch_all(pool)
.await?;
let mut metars = vec![];
for metar_row in metar_rows {
metars.push(Self::from_row(metar_row)?)
}
Ok(metars)
}
pub async fn get_or_update_metars(
state: &AppState,
icaos: &Vec<String>,
) -> CoreResult<Vec<Self>> {
let metars = Self::get_all_distinct(&state.pool, &icaos).await?;
let current_time = Utc::now().timestamp();
let time_offset = env::var("API_METAR_TIME_OFFSET")
.unwrap_or("1800".to_string())
.parse::<i64>()
.unwrap_or(1800);
let short_time_offset: i64 = 300;
// Setup metars and missing metar structures
let mut metars: Vec<Metar> = vec![];
let mut updated_metars: Vec<Self> = vec![];
let mut missing_metar_icaos: Vec<String> = vec![];
let mut found_metar_icaos: HashSet<String> = HashSet::new();
let mut requested_icaos: HashSet<String> = HashSet::from_iter(icao_list.clone());
let mut requested_icaos: HashSet<String> = HashSet::from_iter(icaos.clone());
// Iterate over returned database metars
for metar_row in metar_rows {
let icao = metar_row.icao.clone();
// Remove icao from requested icaos
for metar in metars {
let icao = metar.icao.clone();
// Remove found icao from requested ICAOs
requested_icaos.remove(&icao);
// Handle outdated metars
if current_time > (metar_row.observation_time.timestamp() + time_offset) {
let refresh_seconds = match MetarCheck::get(&icao).await {
// Handle outdated METARs
if current_time > (metar.observation_time.timestamp() + time_offset()) {
// If the METAR has previously been found, get the updated_at time, otherwise default
let refresh_seconds = match MetarCheck::get(state, &icao).await {
Some(c) => current_time - c.updated_at.timestamp(),
None => short_time_offset,
None => DEFAULT_REFRESH_DURATION,
};
// If the metar was cached more than short_time_offset minutes ago, refresh it
if refresh_seconds >= short_time_offset {
// If the metar is outdated, add it to the refresh list
if refresh_seconds >= DEFAULT_REFRESH_DURATION {
log::trace!("{} METAR data is outdated, marked for refresh", &icao);
missing_metar_icaos.push(icao.clone());
}
// Otherwise return outdated data and wait
// Otherwise return the outdated data (to be checked on the next cycle)
else {
log::trace!(
"{} METAR data is outdated; refreshing in {} seconds",
&icao,
short_time_offset - refresh_seconds
DEFAULT_REFRESH_DURATION - refresh_seconds
);
metars.push(Metar::from_db(metar_row)?)
updated_metars.push(metar);
}
}
// Otherwise add the metar to the vector
// Otherwise add the valid metar to the updated list
else {
found_metar_icaos.insert(icao.clone());
let metar_check = MetarCheck::new(icao, true).await;
metar_check.insert(time_offset as u64).await?;
metars.push(Metar::from_db(metar_row)?);
let metar_check = MetarCheck::new(state, icao, true).await;
metar_check.insert(state).await?;
updated_metars.push(metar);
}
}
// Add all metars that were not in the returned database metars
// Add all METARs that were not in the returned database METARs
for icao in &requested_icaos {
match MetarCheck::get(icao).await {
match MetarCheck::get(state, icao).await {
Some(c) => {
if current_time > (c.updated_at.timestamp() + short_time_offset) {
if current_time > (c.updated_at.timestamp() + DEFAULT_REFRESH_DURATION) {
missing_metar_icaos.push(icao.to_string());
}
}
@@ -1075,60 +1170,68 @@ impl Metar {
}
}
// Retrieve missing METARs
if !missing_metar_icaos.is_empty() {
log::trace!(
"Retrieving missing METAR data for {:?}",
missing_metar_icaos
);
let mut remote_metars = Self::get_remote_metars(client, &missing_metar_icaos)
let mut remote_metars = Self::get_remote_metars(&state, &missing_metar_icaos)
.await
.unwrap_or_else(|err| {
log::warn!("Unable to get remote METAR data; {}", err);
vec![]
});
if remote_metars.len() > 0 {
// Insert missing METARs
if remote_metars.len() > 0 {
for remote_metar in remote_metars.clone() {
remote_metar.insert().await?;
remote_metar.insert(&state.pool).await?;
found_metar_icaos.insert(remote_metar.icao.to_string());
let mut metar_check = MetarCheck::new(remote_metar.icao.clone(), true).await;
let mut metar_check = MetarCheck::new(state, remote_metar.icao.clone(), true).await;
metar_check.last_metar = Some(remote_metar);
metar_check.insert(time_offset as u64).await?;
metar_check.insert(state).await?;
}
metars.append(&mut remote_metars);
updated_metars.append(&mut remote_metars);
}
// Update still missing metars
// let mut still_missing_metar_icaos: Vec<String> = vec![];
// Update still missing METARs
for difference in found_metar_icaos.symmetric_difference(&requested_icaos) {
// still_missing_metar_icaos.push(difference.to_string());
let metar_check = MetarCheck::new(difference.to_string(), false).await;
metar_check.insert(short_time_offset as u64).await?;
let metar_check = MetarCheck::new(state, difference.to_string(), false).await;
metar_check.insert(state).await?;
// Only add cached metar data if it's less than 4 hours old
if let Some(last_metar) = metar_check.last_metar {
let four_hours_ago = Utc::now() - chrono::Duration::hours(4);
if last_metar.observation_time < four_hours_ago {
metars.push(last_metar);
updated_metars.push(last_metar);
}
}
}
// if !still_missing_metar_icaos.is_empty() {
// log::trace!("Still missing METAR data from {:?}", still_missing_metar_icaos);
// }
}
Ok(metars)
Ok(updated_metars)
}
pub async fn insert(&self) -> ApiResult<()> {
pub async fn update_metars(state: &AppState, etag: Option<String>) -> CoreResult<String> {
let (remote_metars, etag) = Self::get_cached_remote_metars(state, etag)
.await
.unwrap_or_else(|err| {
log::warn!("Unable to get cached remote METAR data; {}", err);
(vec![], String::new())
});
MetarRow::insert_all(&state.pool, remote_metars).await?;
Ok(etag)
}
pub async fn insert(&self, pool: &Pool<Postgres>) -> CoreResult<()> {
log::trace!(
"Inserting metar {} with observation time {}",
self.icao,
self.observation_time
);
let metar: MetarRow = self.to_db()?;
metar.insert().await?;
let metar: MetarRow = self.to_row()?;
metar.insert(pool).await?;
Ok(())
}
}
@@ -1136,66 +1239,49 @@ impl Metar {
#[cfg(test)]
mod tests {
use super::*;
use chrono::NaiveDateTime;
#[test]
fn test_parse_time() {
for day in 1..=31 {
for hour in 0..24 {
for minute in 0..60 {
// METAR form "DDHHMMZ"
let obs_time = format!("{:02}{:02}{:02}Z", day, hour, minute);
let result = Metar::parse_time(&obs_time);
match result {
Ok(datetime_str) => {
// "YYYY-MM-DDTHH:MM:00Z"
assert_eq!(
datetime_str.len(),
20,
"Unexpected length for input {} yielded {}",
obs_time,
datetime_str
);
// Remove the trailing 'Z' and parse
let trimmed = &datetime_str[..19];
NaiveDateTime::parse_from_str(trimmed, "%Y-%m-%dT%H:%M:%S").unwrap_or_else(|e| {
panic!(
"Parsing '{}' from input {} failed: {}",
trimmed, obs_time, e
)
});
}
Err(_err) => {}
}
}
}
}
}
#[tokio::test]
async fn test_metar() {
let mut metar_string = "METAR KABC 121755Z AUTO 21016G24KT 180V240 1SM R11/P6000FT -RA BR BKN015 OVC025 06/04 A2990
RMK AO2 PK WND 20032/25 WSHFT 1715 VIS 3/4V1 1/2 VIS 3/4 RWY11 RAB07 CIG 013V017 CIG 017 RWY11 PRESFR
SLP125 P0003 60009 T00640036 10066 21012 58033 TSNO $".to_string();
let metar = Metar::parse(&metar_string).unwrap();
async fn test_metar_parse() {
let state = AppState::new().await.unwrap();
let mut metar_string = "METAR KABC 121755Z AUTO 21016G24KT 180V240 1SM R11/P6000FT \
-RA BR BKN015 OVC025 06/04 A2990 RMK AO2 PK WND 20032/25 WSHFT 1715 VIS 3/4V1 1/2 VIS 3/4 \
RWY11 RAB07 CIG 013V017 CIG 017 RWY11 PRESFR SLP125 P0003 60009 T00640036 10066 21012 58033 \
TSNO $"
.to_string();
let metar = Metar::parse(&state.pool, &metar_string).unwrap();
dbg!(&metar.observation_time);
metar_string = "KMIA 090053Z 33004KT 10SM FEW015 FEW024 SCT075 SCT250 25/22 A2990 RMK AO2 SLP126 T02500217 $".to_string();
let metar = Metar::parse(&metar_string).unwrap();
metar_string = "KMIA 090053Z 33004KT 10SM FEW015 FEW024 SCT075 SCT250 25/22 A2990 RMK AO2 \
SLP126 T02500217 $"
.to_string();
let metar = Metar::parse(&state.pool, &metar_string).unwrap();
dbg!(&metar.observation_time);
metar_string =
"KMRB 082253Z 30014G23KT 10SM CLR 05/M12 A3002 RMK AO2 PK WND 30028/2157 SLP168 T00501117"
.to_string();
let metar = Metar::parse(&metar_string).unwrap();
let metar = Metar::parse(&state.pool, &metar_string).unwrap();
dbg!(&metar.observation_time);
metar_string = "KHEF 092356Z 13009KT 10SM CLR 08/M03 A3022 RMK AO2 SLP239 6//// T00831033 10133 20078 53002 PNO $".to_string();
let metar = Metar::parse(&metar_string).unwrap();
metar_string = "KHEF 092356Z 13009KT 10SM CLR 08/M03 A3022 RMK AO2 SLP239 6//// T00831033 \
10133 20078 53002 PNO $"
.to_string();
let metar = Metar::parse(&state.pool, &metar_string).unwrap();
dbg!(&metar.observation_time);
metar_string = "KSLK 162351Z AUTO VRB03KT 1SM -SN BR FEW007 OVC014 00/M02 A2974 RMK AO2 SLP090 P0001 60004 T00001017 10000 21011 53026".to_string();
let metar = Metar::parse(&metar_string).unwrap();
metar_string = "KSLK 162351Z AUTO VRB03KT 1SM -SN BR FEW007 OVC014 00/M02 A2974 RMK AO2 \
SLP090 P0001 60004 T00001017 10000 21011 53026"
.to_string();
let metar = Metar::parse(&state.pool, &metar_string).unwrap();
dbg!(&metar.observation_time);
metar_string = "KABC 121755Z AUTO 21016G24KT 180V240 1SM R11/P6000FT -RA BR BKN015 OVC025 \
SCTCB FEW123TCU 06/04 A2990 RMK AO2 PK WND 20032/25 WSHFT 1715 VIS 3/4V1 1/2 VIS 3/4 RWY11 \
RAB07 CIG 013V017 CIG 017 RWY11 PRESFR SLP125 P0003 60009 T00640036 10066 21012 58033 TSNO $"
.to_string();
let metar = Metar::parse(&state.pool, &metar_string).unwrap();
dbg!(&metar.observation_time);
dbg!(&metar.sky_condition);
}
}

View File

@@ -0,0 +1,113 @@
use crate::error::{CoreError, CoreErrorKind, CoreResult};
use chrono::{Datelike, NaiveDate, Utc};
pub fn parse_metar_time(observation_time: &str) -> CoreResult<String> {
if observation_time.len() != 7 {
return Err(CoreError::new(
CoreErrorKind::InvalidInput,
format!("Unable to parse observation time in {}", observation_time),
));
}
let observation_day = match observation_time[0..2].parse::<u32>() {
Ok(day) => day,
Err(err) => return Err(err.into()),
};
let observation_hour = match observation_time[2..4].parse::<u32>() {
Ok(hour) => hour,
Err(err) => return Err(err.into()),
};
let observation_minute = match observation_time[4..6].parse::<u32>() {
Ok(minute) => minute,
Err(err) => return Err(err.into()),
};
let current_time = Utc::now().naive_utc();
let current_year = current_time.year();
let current_month = current_time.month();
let candidate_date = NaiveDate::from_ymd_opt(current_year, current_month, observation_day)
.ok_or_else(|| {
CoreError::new(
CoreErrorKind::InvalidInput,
format!(
"Invalid date with day {} for current month",
observation_day
),
)
})?;
let candidate_date = match candidate_date.and_hms_opt(observation_hour, observation_minute, 0) {
Some(date) => date,
None => {
return Err(CoreError::new(
CoreErrorKind::InvalidInput,
format!(
"Invalid time for time '{}': hour {}, minute {}",
observation_time, observation_hour, observation_minute
),
));
}
};
let obs_datetime = if candidate_date > current_time {
// Subtract one month. (Handle year rollover carefully.)
let (month, year) = if current_month == 1 {
(12, current_year - 1)
} else {
(current_month - 1, current_year)
};
let adjusted_date = NaiveDate::from_ymd_opt(year, month, observation_day).ok_or_else(|| {
CoreError::new(
CoreErrorKind::InvalidInput,
format!(
"Invalid date with day {} for month {}",
observation_day, month
),
)
})?;
adjusted_date
.and_hms_opt(observation_hour, observation_minute, 0)
.unwrap()
} else {
candidate_date
};
Ok(obs_datetime.format("%Y-%m-%dT%H:%M:00Z").to_string())
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::NaiveDateTime;
#[test]
fn test_parse_metar_time() {
for day in 1..=31 {
for hour in 0..24 {
for minute in 0..60 {
// METAR form "DDHHMMZ"
let obs_time = format!("{:02}{:02}{:02}Z", day, hour, minute);
let result = parse_metar_time(&obs_time);
match result {
Ok(datetime_str) => {
// "YYYY-MM-DDTHH:MM:00Z"
assert_eq!(
datetime_str.len(),
20,
"Unexpected length for input {} yielded {}",
obs_time,
datetime_str
);
// Remove the trailing 'Z' and parse
let trimmed = &datetime_str[..19];
NaiveDateTime::parse_from_str(trimmed, "%Y-%m-%dT%H:%M:%S").unwrap_or_else(|e| {
panic!(
"Parsing '{}' from input {} failed: {}",
trimmed, obs_time, e
)
});
}
Err(_err) => {}
}
}
}
}
}
}

167
crates/lib/src/state.rs Normal file
View File

@@ -0,0 +1,167 @@
use std::env;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use redis::aio::ConnectionManager;
use redis::AsyncTypedCommands;
use s3::{Bucket, BucketConfiguration, Region};
use s3::creds::Credentials;
use sqlx::{Pool, Postgres};
use sqlx::postgres::PgPoolOptions;
use crate::error::CoreResult;
use crate::http_client::HttpClient;
#[derive(Clone)]
pub struct AppState {
pub client: HttpClient,
pub pool: Pool<Postgres>,
pub connection_manager: Arc<Mutex<ConnectionManager>>,
pub bucket: Box<Bucket>,
}
impl AppState {
pub async fn new() -> CoreResult<Self> {
let client = HttpClient::default()?;
let pool: Pool<Postgres> = {
let user = env::var("POSTGRES_USER").unwrap_or("raac".to_string());
let password = env::var("POSTGRES_PASSWORD").expect("POSTGRES_PASSWORD must be set");
let host: String = env::var("POSTGRES_HOST").expect("POSTGRES_HOST must be set");
let port = env::var("POSTGRES_PORT").unwrap_or("5432".to_string());
let name = env::var("POSTGRES_DB").unwrap_or("raac".to_string());
let url = format!(
"postgres://{}:{}@{}:{}/{}",
&user, &password, &host, &port, &name
);
log::info!(
"Connecting to database at postgres://{}:*****@{}:{}/{}...",
&user,
&host,
&port,
&name
);
let connections = env::var("POSTGRES_CONNECTIONS")
.unwrap_or("5".to_string())
.parse::<u32>()
.unwrap_or(5);
let timeout = env::var("POSTGRES_TIMEOUT")
.unwrap_or("30".to_string())
.parse::<u64>()
.unwrap_or(30);
PgPoolOptions::new()
.max_connections(connections)
.acquire_timeout(Duration::from_secs(timeout))
.connect(&url)
.await
.expect("Failed to create postgres pool")
};
let run_migrations = env::var("POSTGRES_MIGRATE")
.unwrap_or("true".to_string())
.parse::<bool>()
.unwrap_or(true);
if run_migrations {
log::debug!("Running database migrations...");
match sqlx::migrate!().run(&pool).await {
Ok(_) => log::debug!("Database migrations completed"),
Err(err) => log::error!("Failed to run database migrations: {}", err),
};
}
let connection_manager: ConnectionManager = {
let host = env::var("VALKEY_HOST").unwrap_or("localhost".to_string());
let port = env::var("VALKEY_PORT").unwrap_or("6379".to_string());
let url = format!("redis://{}:{}", host, port);
log::info!("Connecting to in-memory datastore at {}...", &url);
let client = redis::Client::open(url).expect("Failed to create in-memory datastore client");
ConnectionManager::new(client)
.await
.expect("Failed to create in-memory datastore connection manager")
};
// Setup Bucket connection
let bucket = {
let protocol = std::env::var("MINIO_PROTOCOL").unwrap_or("http".to_string());
let host = std::env::var("MINIO_HOST").unwrap_or("localhost".to_string());
let port = std::env::var("MINIO_PORT").unwrap_or("9000".to_string());
let user = std::env::var("MINIO_ROOT_USER").expect("MINIO_ROOT_USER is not set");
let password = std::env::var("MINIO_ROOT_PASSWORD").expect("MINIO_ROOT_PASSWORD is not set");
let bucket_name = std::env::var("MINIO_BUCKET").unwrap_or("aviation".to_string());
let url = format!("{}://{}:{}", protocol, host, port);
let region = Region::Custom {
region: "".to_string(),
endpoint: url.to_string(),
};
let credentials = Credentials {
access_key: Some(user),
secret_key: Some(password),
security_token: None,
session_token: None,
expiration: None,
};
let bucket = Bucket::new(&bucket_name, region.clone(), credentials.clone())?.with_path_style();
log::info!("Checking for object in bucket at {}", &region.endpoint());
match bucket.head_object("/").await {
Ok(_) => bucket,
Err(_) => {
log::debug!("Creating '{}' bucket", &bucket_name);
let response = match Bucket::create_with_path_style(
&bucket_name,
region,
credentials,
BucketConfiguration::default(),
)
.await
{
Ok(response) => response,
Err(err) => {
log::error!("Failed to create bucket '{}': {}", &bucket_name, err);
return Err(err.into());
}
};
response.bucket
}
}
};
Ok(Self {
client,
pool,
connection_manager: Arc::new(Mutex::new(connection_manager)),
bucket,
})
}
pub async fn set(&self, key: &str, value: &str) -> CoreResult<()> {
let mut connection_manager = self.connection_manager.lock()?;
connection_manager.set(key, value).await?;
Ok(())
}
pub async fn set_ex(&self, key: &str, value: &str, seconds: u64) -> CoreResult<()> {
let mut connection_manager = self.connection_manager.lock()?;
connection_manager.set_ex(key, value, seconds).await?;
Ok(())
}
pub async fn get(&self, key: &str) -> CoreResult<Option<String>> {
let mut connection_manager = self.connection_manager.lock()?;
match connection_manager.get(key).await {
Ok(value) => Ok(value),
Err(_) => Ok(None),
}
}
pub async fn del(&self, key: &str) -> CoreResult<()> {
let mut connection_manager = self.connection_manager.lock()?;
connection_manager.del(key).await?;
Ok(())
}
}

View File

@@ -0,0 +1,11 @@
[package]
name = "scheduler"
version = "0.1.0"
edition = "2024"
[dependencies]
lib = { path = "../lib" }
chrono = "0.4.42"
tokio = { version = "1.47.1", features = ["rt", "rt-multi-thread"] }
log = "0.4.28"
env_logger = "0.11.8"

View File

@@ -0,0 +1,24 @@
# =========
# Builder
# =========
FROM rust:bookworm AS builder
WORKDIR /builder
COPY crates/lib /lib
COPY crates/scheduler/src ./src
COPY crates/scheduler/Cargo.toml ./
RUN apt-get update && apt-get install -y cmake
RUN cargo build --release
# =========
# Runtime
# =========
FROM debian:bookworm-slim AS runtime
WORKDIR /scheduler
RUN apt-get update && apt-get install -y openssl libpq-dev ca-certificates
USER root
COPY --from=builder /builder/target/release/scheduler /usr/local/bin/scheduler
CMD ["scheduler"]

View File

@@ -0,0 +1,56 @@
use chrono::{DateTime, Utc};
use std::env;
use std::time::{Duration, Instant};
use env_logger::Builder;
use log::LevelFilter;
use tokio::time::interval;
use lib::metars::Metar;
use lib::state::AppState;
#[tokio::main]
pub async fn main() {
Builder::new()
.filter_level(LevelFilter::Info) // Set a default log level
.filter_module("scheduler", LevelFilter::Trace)
.filter_module("lib", LevelFilter::Trace)
.init();
let state = match AppState::new().await {
Ok(state) => state,
Err(err) => {
log::error!("Failed to create state: {}", err);
return;
}
};
let seconds = env::var("METAR_INTERVAL")
.unwrap_or("300".to_string())
.parse::<u64>()
.unwrap_or(300);
// Create an interval ticker
let mut interval = interval(Duration::from_secs(seconds));
let mut etag = None;
loop {
interval.tick().await;
// Record start times
let start_monotonic = Instant::now();
let start_utc: DateTime<Utc> = Utc::now();
log::debug!("METAR update started at {}", start_utc);
// Run the update
match Metar::update_metars(&state, etag.clone()).await {
Ok(new_etag) => etag = Some(new_etag),
Err(err) => log::error!("METAR update failed: {}", err),
}
let elapsed = start_monotonic.elapsed();
let next_utc = Utc::now() + chrono::Duration::from_std(Duration::from_secs(seconds)).unwrap();
log::info!(
"METAR update finished in {:.2?}; next run at {}",
elapsed,
next_utc
);
}
}

View File

@@ -14,7 +14,7 @@ services:
container_name: aviation-nginx
build:
context: .
dockerfile: Dockerfile
dockerfile: nginx/Dockerfile
env_file: *env
environment:
SSL_CERT_PATH: /etc/nginx/ssl/localhost.crt
@@ -25,8 +25,7 @@ services:
volumes:
- ./ssl:/etc/nginx/ssl/
networks:
- frontend
- backend
- web
<<: *default_restart
postgres:
@@ -42,32 +41,28 @@ services:
- postgres_logs:/var/log
ports:
- "${POSTGRES_PORT:-5432}:5432"
networks:
- backend
profiles:
- backend
<<: *default_restart
redis:
image: gitea.bensherriff.com/homelab/redis:8.0-M03
container_name: aviation-redis
valkey:
image: valkey/valkey:8.1.3
container_name: aviation-valkey
volumes:
- redis:/data
- valkey:/data
ports:
- "${REDIS_PORT:-6379}:6379"
- "${VALKEY_PORT:-6379}:6379"
healthcheck:
test: [ "CMD", "redis-cli", "--raw", "incr", "ping" ]
test: [ "CMD", "valkey-cli", "--raw", "incr", "ping" ]
interval: 10s
timeout: 5s
retries: 3
networks:
- backend
profiles:
- backend
<<: *default_restart
minio:
image: gitea.bensherriff.com/homelab/minio:RELEASE.2025-02-28T09-55-16Z
image: minio/minio:RELEASE.2025-07-23T15-54-02Z
container_name: aviation-minio
environment:
MINIO_ROOT_USER: ${MINIO_ROOT_USER}
@@ -79,8 +74,6 @@ services:
ports:
- "${MINIO_PORT:-9000}:9000"
- "${MINIO_INTERNAL_PORT:-9001}:9001"
networks:
- backend
profiles:
- backend
command: server --console-address ":9001" /data
@@ -91,15 +84,15 @@ services:
container_name: aviation-api
build:
context: .
dockerfile: Dockerfile
dockerfile: crates/api/Dockerfile
env_file: *env
environment:
SSL_CA_PATH: /ssl/ca.pem
API_PORT: 5000
POSTGRES_HOST: aviation-postgres
POSTGRES_PORT: 5432
REDIS_HOST: aviation-redis
REDIS_PORT: 6379
VALKEY_HOST: aviation-valkey
VALKEY_PORT: 6379
MINIO_HOST: aviation-minio
MINIO_PORT: 9000
TEMPLATE_DIR: /templates
@@ -110,43 +103,52 @@ services:
- "${API_PORT:-5000}:5000"
depends_on:
- postgres
- redis
- valkey
- minio
networks:
- frontend
- backend
profiles:
- api
<<: *default_restart
ui-dev:
image: gitea.bensherriff.com/bsherriff/aviation-ui:latest
container_name: aviation-ui-dev
scheduler:
image: gitea.bensherriff.com/bsherriff/aviation-scheduler:latest
container_name: aviation-scheduler
build:
context: .
dockerfile: Dockerfile
dockerfile: crates/scheduler/Dockerfile
env_file: *env
environment:
- VITE_NODE_ENV=${VITE_NODE_ENV:-development}
ports:
- "${UI_PORT:-3000}:3000"
volumes:
- ./ui/src:/app/src
- ./ui/public:/app/public
- ./ui/styles:/app/styles
networks:
- frontend
POSTGRES_HOST: aviation-postgres
POSTGRES_PORT: 5432
depends_on:
- postgres
profiles:
- frontend
command: ["npm", "run", "dev"]
- api
<<: *default_restart
mailpit:
image: axllent/mailpit
container_name: mailpit
environment:
MP_MAX_MESSAGES: 5000
MP_DATABASE: /data/mailpit.db
MP_SMTP_AUTH_ACCEPT_ANY: 1
MP_SMTP_AUTH_ALLOW_INSECURE: 1
ports:
- "${MAILPIT_WEB_PORT:-8025}:8025"
- "${MAILPIT_SMTP_PORT:-1025}:1025"
volumes:
- mailpit:/data
profiles:
- dev
<<: *default_restart
volumes:
postgres:
postgres_logs:
redis:
valkey:
minio:
mailpit:
networks:
frontend:
backend:
web:
driver: bridge

View File

@@ -4,12 +4,10 @@ worker_processes auto;
error_log /var/log/nginx/error.log notice;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
@@ -20,12 +18,16 @@ http {
access_log /var/log/nginx/access.log main;
# allow HTTP/2 on the frontend
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
sendfile on;
#tcp_nopush on;
tcp_nopush on;
keepalive_timeout 65;
#gzip on;
gzip on;
# Set client limit to 100 MB
client_max_body_size 100M;

View File

@@ -1,3 +1,3 @@
[toolchain]
channel = "stable"
channel = "nightly"
components = ["rustfmt", "clippy"]

6
rustfmt.toml Normal file
View File

@@ -0,0 +1,6 @@
indent_style = "Block"
reorder_imports = true
imports_layout = "HorizontalVertical"
imports_granularity = "Crate"
group_imports = "One"
tab_spaces = 2

View File

@@ -2,6 +2,7 @@
force=0
push=0
push_all=0
API_VERSION=$(sed -n 's/^version *= *"\([^"]*\)".*/\1/p' "$(pwd)"/api/Cargo.toml)
UI_VERSION=$(sed -n 's/.*"version": *"\([^"]*\)".*/\1/p' "$(pwd)"/ui/package.json)
@@ -17,6 +18,13 @@ for arg in "$@"; do
push=1
shift
;;
-a|--push-all)
push_all=1
shift
;;
*)
shift
;;
esac
done
@@ -69,3 +77,14 @@ if echo "$changed_files" | grep -q "^api/"; then
fi
fi
fi
# Push all tags
if [ $push_all -eq 1 ]; then
if [ $force -eq 1 ]; then
echo "Force-pushing ALL tags to remote"
git push -f origin --tags
else
echo "Pushing ALL tags to remote"
git push origin --tags
fi
fi

183
ui/package-lock.json generated
View File

@@ -65,15 +65,15 @@
}
},
"node_modules/@babel/code-frame": {
"version": "7.26.2",
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.26.2.tgz",
"integrity": "sha512-RJlIHRueQgwWitWgF8OdFYGZX328Ax5BCemNGlqHfplnRT9ESi8JkFlvaVYbS+UubVY6dpv87Fs2u5M29iNFVQ==",
"version": "7.27.1",
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.27.1.tgz",
"integrity": "sha512-cjQ7ZlQ0Mv3b47hABuTevyTuYN4i+loJKGeV9flcCgIK37cCXRh+L1bd3iBHlynerhQ7BhCkn2BPbQUL+rGqFg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/helper-validator-identifier": "^7.25.9",
"@babel/helper-validator-identifier": "^7.27.1",
"js-tokens": "^4.0.0",
"picocolors": "^1.0.0"
"picocolors": "^1.1.1"
},
"engines": {
"node": ">=6.9.0"
@@ -197,9 +197,9 @@
}
},
"node_modules/@babel/helper-string-parser": {
"version": "7.25.9",
"resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.25.9.tgz",
"integrity": "sha512-4A/SCr/2KLd5jrtOMFzaKjVtAei3+2r/NChoBNoZ3EyP/+GlhoaEGoWOZUmFmoITP7zOJyHIMm+DYRd8o3PvHA==",
"version": "7.27.1",
"resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz",
"integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==",
"dev": true,
"license": "MIT",
"engines": {
@@ -207,9 +207,9 @@
}
},
"node_modules/@babel/helper-validator-identifier": {
"version": "7.25.9",
"resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.25.9.tgz",
"integrity": "sha512-Ed61U6XJc3CVRfkERJWDz4dJwKe7iLmmJsbOGu9wSloNSFttHV0I8g6UAgb7qnK5ly5bGLPd4oXZlxCdANBOWQ==",
"version": "7.27.1",
"resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.27.1.tgz",
"integrity": "sha512-D2hP9eA+Sqx1kBZgzxZh0y1trbuU+JoDkiEwqhQ36nodYqJwyEIhPSdMNd7lOm/4io72luTPWH20Yda0xOuUow==",
"dev": true,
"license": "MIT",
"engines": {
@@ -227,27 +227,27 @@
}
},
"node_modules/@babel/helpers": {
"version": "7.26.9",
"resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.26.9.tgz",
"integrity": "sha512-Mz/4+y8udxBKdmzt/UjPACs4G3j5SshJJEFFKxlCGPydG4JAHXxjWjAwjd09tf6oINvl1VfMJo+nB7H2YKQ0dA==",
"version": "7.27.1",
"resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.27.1.tgz",
"integrity": "sha512-FCvFTm0sWV8Fxhpp2McP5/W53GPllQ9QeQ7SiqGWjMf/LVG07lFa5+pgK05IRhVwtvafT22KF+ZSnM9I545CvQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/template": "^7.26.9",
"@babel/types": "^7.26.9"
"@babel/template": "^7.27.1",
"@babel/types": "^7.27.1"
},
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/parser": {
"version": "7.26.9",
"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.26.9.tgz",
"integrity": "sha512-81NWa1njQblgZbQHxWHpxxCzNsa3ZwvFqpUg7P+NNUU6f3UU2jBEg4OlF/J6rl8+PQGh1q6/zWScd001YwcA5A==",
"version": "7.27.2",
"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.27.2.tgz",
"integrity": "sha512-QYLs8299NA7WM/bZAdp+CviYYkVoYXlDW2rzliy3chxd1PQjej7JORuMJDJXJUb9g0TT+B99EwaVLKmX+sPXWw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/types": "^7.26.9"
"@babel/types": "^7.27.1"
},
"bin": {
"parser": "bin/babel-parser.js"
@@ -289,27 +289,24 @@
}
},
"node_modules/@babel/runtime": {
"version": "7.26.9",
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.26.9.tgz",
"integrity": "sha512-aA63XwOkcl4xxQa3HjPMqOP6LiK0ZDv3mUPYEFXkpHbaFjtGggE1A61FjFzJnB+p7/oy2gA8E+rcBNl/zC1tMg==",
"version": "7.27.1",
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.27.1.tgz",
"integrity": "sha512-1x3D2xEk2fRo3PAhwQwu5UubzgiVWSXTBfWpVd2Mx2AzRqJuDJCsgaDVZ7HB5iGzDW1Hl1sWN2mFyKjmR9uAog==",
"license": "MIT",
"dependencies": {
"regenerator-runtime": "^0.14.0"
},
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/template": {
"version": "7.26.9",
"resolved": "https://registry.npmjs.org/@babel/template/-/template-7.26.9.tgz",
"integrity": "sha512-qyRplbeIpNZhmzOysF/wFMuP9sctmh2cFzRAZOn1YapxBsE1i9bJIY586R/WBLfLcmcBlM8ROBiQURnnNy+zfA==",
"version": "7.27.2",
"resolved": "https://registry.npmjs.org/@babel/template/-/template-7.27.2.tgz",
"integrity": "sha512-LPDZ85aEJyYSd18/DkjNh4/y1ntkE5KwUHWTiqgRxruuZL2F1yuHligVHLvcHY2vMHXttKFpJn6LwfI7cw7ODw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/code-frame": "^7.26.2",
"@babel/parser": "^7.26.9",
"@babel/types": "^7.26.9"
"@babel/code-frame": "^7.27.1",
"@babel/parser": "^7.27.2",
"@babel/types": "^7.27.1"
},
"engines": {
"node": ">=6.9.0"
@@ -345,14 +342,14 @@
}
},
"node_modules/@babel/types": {
"version": "7.26.9",
"resolved": "https://registry.npmjs.org/@babel/types/-/types-7.26.9.tgz",
"integrity": "sha512-Y3IR1cRnOxOCDvMmNiym7XpXQ93iGDDPHx+Zj+NM+rg0fBaShfQLkg+hKPaZCEvg5N/LeCo4+Rj/i3FuJsIQaw==",
"version": "7.27.1",
"resolved": "https://registry.npmjs.org/@babel/types/-/types-7.27.1.tgz",
"integrity": "sha512-+EzkxvLNfiUeKMgy/3luqfsCWFRXLb7U6wNQTk60tovuckwB15B191tJWvpp4HjiQWdJkCxO3Wbvc6jlk3Xb2Q==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/helper-string-parser": "^7.25.9",
"@babel/helper-validator-identifier": "^7.25.9"
"@babel/helper-string-parser": "^7.27.1",
"@babel/helper-validator-identifier": "^7.27.1"
},
"engines": {
"node": ">=6.9.0"
@@ -1571,12 +1568,6 @@
"@babel/types": "^7.20.7"
}
},
"node_modules/@types/cookie": {
"version": "0.6.0",
"resolved": "https://registry.npmjs.org/@types/cookie/-/cookie-0.6.0.tgz",
"integrity": "sha512-4Kh9a6B2bQciAhf7FSuMRRkUWecJgJu9nPnx3yzpsfXX/c50REIqpHY4C82bXP90qrLtXtkDxTZosYO3UpOwlA==",
"license": "MIT"
},
"node_modules/@types/d3": {
"version": "7.4.3",
"resolved": "https://registry.npmjs.org/@types/d3/-/d3-7.4.3.tgz",
@@ -4405,15 +4396,13 @@
}
},
"node_modules/react-router": {
"version": "7.5.0",
"resolved": "https://registry.npmjs.org/react-router/-/react-router-7.5.0.tgz",
"integrity": "sha512-estOHrRlDMKdlQa6Mj32gIks4J+AxNsYoE0DbTTxiMy2mPzZuWSDU+N85/r1IlNR7kGfznF3VCUlvc5IUO+B9g==",
"version": "7.6.0",
"resolved": "https://registry.npmjs.org/react-router/-/react-router-7.6.0.tgz",
"integrity": "sha512-GGufuHIVCJDbnIAXP3P9Sxzq3UUsddG3rrI3ut1q6m0FI6vxVBF3JoPQ38+W/blslLH4a5Yutp8drkEpXoddGQ==",
"license": "MIT",
"dependencies": {
"@types/cookie": "^0.6.0",
"cookie": "^1.0.1",
"set-cookie-parser": "^2.6.0",
"turbo-stream": "2.4.0"
"set-cookie-parser": "^2.6.0"
},
"engines": {
"node": ">=20.0.0"
@@ -4493,12 +4482,6 @@
"pify": "^2.3.0"
}
},
"node_modules/regenerator-runtime": {
"version": "0.14.1",
"resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.14.1.tgz",
"integrity": "sha512-dYnhHh0nJoMfnkZs6GmmhFknAGRrLznOu5nc9ML+EJxGvrx6H7teuevqVqCuPcPK//3eDrrjQhehXVx9cnkGdw==",
"license": "MIT"
},
"node_modules/require-directory": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
@@ -4845,6 +4828,51 @@
"integrity": "sha512-Cat63mxsVJlzYvN51JmVXIgNoUokrIaT2zLclCXjRd8boZ0004U4KCs/sToJ75C6sdlByWxpYnb5Boif1VSFew==",
"license": "MIT"
},
"node_modules/tinyglobby": {
"version": "0.2.13",
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.13.tgz",
"integrity": "sha512-mEwzpUgrLySlveBwEVDMKk5B57bhLPYovRfPAXD5gA/98Opn0rCDj3GtLwFvCvH5RK9uPCExUROW5NjDwvqkxw==",
"dev": true,
"license": "MIT",
"dependencies": {
"fdir": "^6.4.4",
"picomatch": "^4.0.2"
},
"engines": {
"node": ">=12.0.0"
},
"funding": {
"url": "https://github.com/sponsors/SuperchupuDev"
}
},
"node_modules/tinyglobby/node_modules/fdir": {
"version": "6.4.4",
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.4.4.tgz",
"integrity": "sha512-1NZP+GK4GfuAv3PqKvxQRDMjdSRZjnkq7KfhlNrCNNlZ0ygQFpebfrnfnq/W7fpUnAv9aGWmY1zKx7FYL3gwhg==",
"dev": true,
"license": "MIT",
"peerDependencies": {
"picomatch": "^3 || ^4"
},
"peerDependenciesMeta": {
"picomatch": {
"optional": true
}
}
},
"node_modules/tinyglobby/node_modules/picomatch": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.2.tgz",
"integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/sponsors/jonschlinkert"
}
},
"node_modules/to-regex-range": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",
@@ -4877,12 +4905,6 @@
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"license": "0BSD"
},
"node_modules/turbo-stream": {
"version": "2.4.0",
"resolved": "https://registry.npmjs.org/turbo-stream/-/turbo-stream-2.4.0.tgz",
"integrity": "sha512-FHncC10WpBd2eOmGwpmQsWLDoK4cqsA/UT/GqNoaKOQnT8uzhtCbg3EoUDMvqpOSAI0S26mr0rkjzbOO6S3v1g==",
"license": "ISC"
},
"node_modules/type-check": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz",
@@ -5089,15 +5111,18 @@
"license": "MIT"
},
"node_modules/vite": {
"version": "6.2.1",
"resolved": "https://registry.npmjs.org/vite/-/vite-6.2.1.tgz",
"integrity": "sha512-n2GnqDb6XPhlt9B8olZPrgMD/es/Nd1RdChF6CBD/fHW6pUyUTt2sQW2fPRX5GiD9XEa6+8A6A4f2vT6pSsE7Q==",
"version": "6.3.5",
"resolved": "https://registry.npmjs.org/vite/-/vite-6.3.5.tgz",
"integrity": "sha512-cZn6NDFE7wdTpINgs++ZJ4N49W2vRp8LCKrn3Ob1kYNtOo21vfDoaV5GzBfLU4MovSAB8uNRm4jgzVQZ+mBzPQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"esbuild": "^0.25.0",
"fdir": "^6.4.4",
"picomatch": "^4.0.2",
"postcss": "^8.5.3",
"rollup": "^4.30.1"
"rollup": "^4.34.9",
"tinyglobby": "^0.2.13"
},
"bin": {
"vite": "bin/vite.js"
@@ -5160,6 +5185,34 @@
}
}
},
"node_modules/vite/node_modules/fdir": {
"version": "6.4.4",
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.4.4.tgz",
"integrity": "sha512-1NZP+GK4GfuAv3PqKvxQRDMjdSRZjnkq7KfhlNrCNNlZ0ygQFpebfrnfnq/W7fpUnAv9aGWmY1zKx7FYL3gwhg==",
"dev": true,
"license": "MIT",
"peerDependencies": {
"picomatch": "^3 || ^4"
},
"peerDependenciesMeta": {
"picomatch": {
"optional": true
}
}
},
"node_modules/vite/node_modules/picomatch": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.2.tgz",
"integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/sponsors/jonschlinkert"
}
},
"node_modules/which": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",

View File

@@ -1,12 +1,12 @@
/* Set up Flexbox layout */
.App {
display: flex;
flex-direction: column;
html, body, #root {
height: 100%;
}
.map-wrapper {
display: flex;
flex-direction: column;
flex: 1;
min-height: 0;
}
.leaflet-container {

View File

@@ -6,7 +6,6 @@ import markerIcon2x from 'leaflet/dist/images/marker-icon-2x.png';
import markerIcon from 'leaflet/dist/images/marker-icon.png';
import markerShadow from 'leaflet/dist/images/marker-shadow.png';
import L from 'leaflet';
import { Header } from '@components/Header';
import AirportLayer from '@components/AirportLayer.tsx';
import { useEffect, useState } from 'react';
import { Airport } from '@lib/airport.types.ts';
@@ -90,10 +89,9 @@ function App() {
}
return (
<div className='App'>
<Header />
<div className='map-wrapper'>
<div className='map-wrapper' style={{ flex: 1, minHeight: 0 }}>
<MapContainer
style={{ height: '100%', width: '100%' }}
className='leaflet-container'
attributionControl={false}
center={defaultCenter}
@@ -106,6 +104,7 @@ function App() {
]}
scrollWheelZoom={true}
zoomControl={false}
markerZoomAnimation={false}
>
<AirportDrawer airport={airport} setAirport={setAirport} />
<LayersControl>
@@ -139,7 +138,6 @@ function App() {
/>
</MapContainer>
</div>
</div>
);
}

View File

@@ -1,4 +1,3 @@
import { Header } from '@components/Header';
import { useUserContext } from '@components/context/UserContext.tsx';
import { AirportTable } from '@components/AirportTable';
import { AirportDrop } from '@components/AirportDrop';
@@ -13,7 +12,6 @@ export function Administration() {
return (
<>
<Header />
<AirportTable />
<AirportDrop />
</>

View File

@@ -2,9 +2,11 @@ import {
Accordion,
Badge,
Box,
Button,
Divider,
Drawer,
Group,
Stack,
Tabs,
TabsList,
Text,
@@ -14,13 +16,14 @@ import {
import { Airport, AirportCategory } from '@lib/airport.types.ts';
import { getMarkerColor, Metar } from '@lib/metar.types.ts';
import { CSSProperties, forwardRef, ReactNode, useEffect, useState } from 'react';
import { getMetars } from '@lib/metar.ts';
import { useMediaQuery } from '@mantine/hooks';
import { IconViewfinder } from '@tabler/icons-react';
import { IconStar, IconStarFilled, IconViewfinder } from '@tabler/icons-react';
import { RunwayTable } from '@components/AirportDrawer/RunwayTable.tsx';
import { CommunicationTable } from '@components/AirportDrawer/CommunicationTable.tsx';
import { useMap } from 'react-leaflet';
import type { Map as LeafletMap } from 'leaflet';
import { getMetars } from '@lib/metar.ts';
import { useUserContext } from '@components/context/UserContext.tsx';
export function AirportDrawer({
airport,
@@ -29,6 +32,9 @@ export function AirportDrawer({
airport: Airport | null;
setAirport: (airport: Airport | null) => void;
}) {
const { user, favorites, toggleFavorite } = useUserContext();
const isAdmin = user?.role === 'ADMIN';
const isFavorite = airport ? favorites.includes(airport.icao) : false;
const [metar, setMetar] = useState<Metar | undefined>(undefined);
const isMobile = useMediaQuery('(max-width: 768px)');
const map = useMap();
@@ -65,7 +71,7 @@ export function AirportDrawer({
onClose={() => setAirport(null)}
withinPortal
zIndex={1000}
styles={{ root: { padding: 0, margin: 0, width: 0, height: 0, backgroundColor: 'red' } }}
styles={{ root: { padding: 0, margin: 0, width: 0, height: 0 } }}
padding='md'
size={isMobile ? '100%' : 'md'}
position='left'
@@ -73,6 +79,15 @@ export function AirportDrawer({
>
<Drawer.Content>
<Drawer.Header>
{user && (
<UnstyledButton
onClick={() => toggleFavorite(airport.icao)}
aria-label={isFavorite ? 'Unfavorite airport' : 'Favorite airport'}
style={{ padding: 4 }}
>
{isFavorite ? <IconStarFilled size={24} color='#faca15' /> : <IconStar size={24} />}
</UnstyledButton>
)}
<Drawer.Title>
<Text size={'xl'}>{airport.name}</Text>
</Drawer.Title>
@@ -104,6 +119,7 @@ export function AirportDrawer({
<TabsList grow>
<Tabs.Tab value={'info'}>Info</Tabs.Tab>
<Tabs.Tab value={'weather'}>Weather</Tabs.Tab>
{user && <Tabs.Tab value={'manage'}>Manage</Tabs.Tab>}
</TabsList>
<Tabs.Panel value={'info'}>
<AirportInfo map={map} airport={airport} />
@@ -111,6 +127,23 @@ export function AirportDrawer({
<Tabs.Panel value={'weather'}>
<WeatherInfo metar={airport.latest_metar} />
</Tabs.Panel>
{user && (
<Tabs.Panel value={'manage'}>
{isAdmin ? (
<Stack mt='md'>
<Button onClick={() => {}}>Update METAR</Button>
<Button onClick={() => {}}>Edit Airport</Button>
<Button color='red' onClick={() => {}}>
Delete Airport
</Button>
</Stack>
) : (
<Stack mt='md'>
<Button onClick={() => {}}>Request Edit</Button>
</Stack>
)}
</Tabs.Panel>
)}
</Tabs>
</Box>
</Drawer.Body>
@@ -204,11 +237,89 @@ function AirportInfo({ map, airport }: { map: LeafletMap; airport: Airport }) {
}
function WeatherInfo({ metar }: { metar?: Metar }) {
if (metar) {
return <>{metar.raw_text}</>;
} else {
return <>No METAR observation available</>;
if (!metar) {
return <>No METAR observation available/</>;
}
return (
<Box>
<Text size={'xs'} color={'dimmed'} mt={'xs'}>
Raw METAR
</Text>
<Text size={'sm'} mb={'md'}>
{metar.raw_text}
</Text>
<Group mb={'xs'}>
{metar.report_modifier && <Badge>{metar.report_modifier}</Badge>}
{metar.becoming_change && <Badge>TEMPO/BCMG</Badge>}
{metar.temporary_change && <Badge>TEMPO</Badge>}
{metar.no_significant_change && <Badge>No Change</Badge>}
</Group>
<Text size={'xs'} color={'dimmed'}>
Observation Time
</Text>
<Text size={'sm'} mb={'md'}>
{new Date(metar.observation_time).toLocaleString()}
</Text>
{metar.wind_dir_degrees && metar.wind_speed_kt != null && (
<Text mb='sm'>
<strong>Wind:</strong> {metar.wind_dir_degrees}° at {metar.wind_speed_kt} kt
{metar.wind_gust_kt && `, gusts ${metar.wind_gust_kt} kt`}
{metar.variable_wind_dir_degrees && ` (variable ${metar.variable_wind_dir_degrees})`}
</Text>
)}
{metar.visibility_statute_mi && (
<Text mb='sm'>
<strong>Visibility:</strong> {metar.visibility_statute_mi} statute miles
</Text>
)}
{(metar.temp_c != null || metar.dew_point_c != null) && (
<Text mb='sm'>
<strong>Temp / Dew Point:</strong> {metar.temp_c}°C / {metar.dew_point_c}°C
{metar.estimated_humidity != null && ` (${metar.estimated_humidity}% RH)`}
</Text>
)}
{(metar.altimeter_in_hg != null || metar.sea_level_pressure_mb != null) && (
<Text mb='sm'>
<strong>Pressure:</strong>
{metar.altimeter_in_hg != null && ` Alt ${metar.altimeter_in_hg} inHg`}
{metar.sea_level_pressure_mb != null && `, SLP ${metar.sea_level_pressure_mb} mb`}
</Text>
)}
{metar.weather_phenomena.length > 0 && (
<Text mb='sm'>
<strong>Weather:</strong> {metar.weather_phenomena.join(', ')}
</Text>
)}
{metar.sky_condition.length > 0 && (
<Text mb='sm'>
<strong>Sky:</strong>{' '}
{metar.sky_condition
.map((s) => `${s.sky_cover}${s.cloud_base_ft_agl ? ` at ${s.cloud_base_ft_agl} ft` : ''}`)
.join(', ')}
</Text>
)}
{metar.max_temp_c != null && metar.min_temp_c != null && (
<Text mb='sm'>
<strong>Max / Min:</strong> {metar.max_temp_c}°C / {metar.min_temp_c}°C
</Text>
)}
{metar.density_altutude != null && (
<Text mb='sm'>
<strong>Density Altitude:</strong> {metar.density_altutude} ft
</Text>
)}
</Box>
);
}
function airportCategoryToText(category: AirportCategory): string {

View File

@@ -5,8 +5,7 @@ import debounce from 'lodash.debounce';
import { getAirports } from '@lib/airport.ts';
import AirportMarker from '@components/AirportMarker.tsx';
import { LayerInfo } from '@/App.tsx';
const EXPANSION_FACTOR = 0.5;
import { LatLng } from 'leaflet';
export default function AirportLayer({
setAirport,
@@ -18,21 +17,13 @@ export default function AirportLayer({
selectedLayer: LayerInfo;
}) {
const [airports, setAirports] = useState<Airport[]>([]);
const lastBoundsRef = useRef<{ ne: any; sw: any } | null>(null);
const lastBoundsRef = useRef<{ ne: LatLng; sw: LatLng } | null>(null);
const debouncedLoad = useRef(
debounce(async (map: any) => {
const b = map.getBounds();
const north = b.getNorth(),
south = b.getSouth();
const east = b.getEast(),
west = b.getWest();
const latDelta = (north - south) * EXPANSION_FACTOR;
const lonDelta = (east - west) * EXPANSION_FACTOR;
// expanded bbox
const ne = { lat: north + latDelta, lon: east + lonDelta };
const sw = { lat: south - latDelta, lon: west - lonDelta };
const bounds = map.getBounds();
const ne = bounds.getNorthEast();
const sw = bounds.getSouthWest();
lastBoundsRef.current = { ne, sw };
try {
@@ -58,7 +49,7 @@ export default function AirportLayer({
return () => {
debouncedLoad.cancel();
};
}, [map]);
}, [map, debouncedLoad]);
return (
<>

View File

@@ -0,0 +1,62 @@
import { useEffect, useState } from 'react';
import { useDebouncedValue } from '@mantine/hooks';
import { getAirports } from '@lib/airport.ts';
import { Autocomplete } from '@mantine/core';
export interface AirportSearchProps {
limit?: number;
}
export function AirportSearch({ limit = 5 }: AirportSearchProps) {
const [search, setSearch] = useState('');
const [debounced] = useDebouncedValue(search, 300);
const [data, setData] = useState<{ key: string; value: string; label: string }[]>([]);
useEffect(() => {
if (!debounced) {
setData([]);
return;
}
async function fetch(): Promise<{ key: string; value: string; label: string }[]> {
try {
const icaoResponse = await getAirports({
icaos: [debounced],
limit: 1
});
const nameResponse = await getAirports({
name: debounced,
limit: limit - 1
});
let combined = [...icaoResponse.data, ...nameResponse.data];
combined = combined.slice(0, limit);
return combined.map((airport) => ({
key: airport.icao,
value: airport.icao,
label: `${airport.icao} - ${airport.name}`
}));
} catch (err) {
console.error('airport search failed', err);
return [];
}
}
fetch().then((d) => {
setData(d);
console.log(d);
});
}, [debounced, limit]);
return (
<Autocomplete
placeholder='Enter airport name or ICAO'
value={search}
onChange={setSearch}
data={data}
limit={limit}
onOptionSubmit={() => {}}
radius={'xl'}
onBlur={() => setSearch('')}
/>
);
}

View File

@@ -0,0 +1,28 @@
.footer {
height: 48px;
background: #2b2d31;
border-top: 1px solid light-dark(var(--mantine-color-gray-3), var(--mantine-color-dark-4));
}
.inner {
height: 48px;
display: flex;
justify-content: space-between;
align-items: center;
padding: var(--mantine-spacing-xs) var(--mantine-spacing-md);
@media (max-width: $mantine-breakpoint-xs) {
flex-direction: column;
}
}
.link {
color: light-dark(var(--mantine-color-gray-7), var(--mantine-color-dark-0));
@media (max-width: $mantine-breakpoint-xs) {
margin-top: var(--mantine-spacing-md);
}
}
.link:hover {
color: light-dark(var(--mantine-color-white));
}

View File

@@ -0,0 +1,53 @@
import classes from './Footer.module.css';
import { Divider, Group, Text } from '@mantine/core';
import { useEffect, useState } from 'react';
import { systemInfo } from '@lib/system.ts';
import { useMediaQuery } from '@mantine/hooks';
const links = [
{ link: `/swagger/`, newTab: true, label: 'API Docs' },
{ link: '/cookies', label: 'Cookies' },
{ link: '/privacy', label: 'Privacy' },
{ link: '/terms', label: 'Terms' },
{ link: '/contact', label: 'Contact' }
];
export function Footer() {
const [version, setVersion] = useState('0.0.0');
const isMobile = useMediaQuery('(max-width: 768px)');
const items = links.map((link) => (
<a className={classes.link} key={link.label} href={link.link} target={link.newTab ? `_blank` : ''}>
<Text size='sm'>{link.label}</Text>
</a>
));
useEffect(() => {
systemInfo().then((info) => {
if (info != undefined) {
setVersion(info.version);
}
});
}, []);
return (
<div className={classes.footer}>
<Group className={classes.inner}>
<Group>
<Text size='sm'>
API{' '}
<a className={classes.link} href={'https://gitea.bensherriff.com/bsherriff/aviation'} target={'_blank'}>
v{version}
</a>
</Text>
<Divider orientation={'vertical'} />
<Text size='sm'>© {new Date().getFullYear()} bensherriff.com</Text>
</Group>
{!isMobile && (
<Group gap='xs' justify='flex-end' wrap='nowrap'>
{items}
</Group>
)}
</Group>
</div>
);
}

View File

@@ -2,7 +2,7 @@
height: 56px;
padding: 0 16px 0 16px;
/*background-color: var(--mantine-color-body);*/
background: #32495f;
background: #2b2d31;
border-bottom: 1px solid light-dark(var(--mantine-color-gray-3), var(--mantine-color-dark-4));
}

View File

@@ -17,46 +17,46 @@ import Cookies from 'js-cookie';
interface HeaderModalProps {
type?: string;
toggle: (input: string | undefined) => void;
login: ({ email, password }: { email: string; password: string }) => Promise<boolean>;
login: ({ username, password }: { username: string; password: string }) => Promise<boolean>;
register: ({
firstName,
lastName,
email,
username,
password
}: {
firstName: string;
lastName: string;
email: string;
username: string;
password: string;
}) => Promise<boolean>;
}
export function HeaderModal({ type, toggle, login, register }: HeaderModalProps) {
function passwordValidator(value: string) {
if (value.trim().length < 8) {
return 'Password must be at least 8 characters';
if (value.trim().length < 6) {
return 'Password must be at least 6 characters';
}
if (value.trim().length >= 128) {
return 'Password must be at most 128 characters';
}
if (!/(\d)/.test(value)) {
return 'Password must contain at least one number';
}
if (!/[a-z]/.test(value)) {
return 'Password must contain at least one lowercase letter';
}
if (!/[A-Z]/.test(value)) {
return 'Password must contain at least one uppercase letter';
}
if (!/[!@#$%^&*]/.test(value)) {
return 'Password must contain at least one special character';
}
// if (!/(\d)/.test(value)) {
// return 'Password must contain at least one number';
// }
// if (!/[a-z]/.test(value)) {
// return 'Password must contain at least one lowercase letter';
// }
// if (!/[A-Z]/.test(value)) {
// return 'Password must contain at least one uppercase letter';
// }
// if (!/[!@#$%^&*]/.test(value)) {
// return 'Password must contain at least one special character';
// }
return null;
}
function emailValidator(value: string) {
if (value.trim().length == 0) {
return 'Email is required';
return null;
}
if (!/^\S+@\S+$/.test(value)) {
return 'Invalid email';
@@ -68,12 +68,14 @@ export function HeaderModal({ type, toggle, login, register }: HeaderModalProps)
initialValues: {
firstName: '',
lastName: '',
username: '',
email: '',
password: ''
},
validate: {
firstName: (value) => (value.trim().length > 0 ? null : 'First name is required'),
lastName: (value) => (value.trim().length > 0 ? null : 'Last name is required'),
username: (value) => (value.trim().length > 0 ? null : 'Username is required'),
email: emailValidator,
password: passwordValidator
}
@@ -81,7 +83,7 @@ export function HeaderModal({ type, toggle, login, register }: HeaderModalProps)
const loginForm = useForm({
initialValues: {
email: Cookies.get('email') || '',
username: Cookies.get('username') || '',
password: '',
remember: Cookies.get('remember') === 'true'
}
@@ -150,14 +152,20 @@ export function HeaderModal({ type, toggle, login, register }: HeaderModalProps)
{...registerForm.getInputProps('lastName')}
/>
<TextInput
label='Email'
placeholder='you@example.com'
label='Username'
placeholder='Your username'
required
{...registerForm.getInputProps('username')}
/>
<TextInput
label='Email'
description={'Optional for email verification and updates'}
placeholder='you@example.com'
{...registerForm.getInputProps('email')}
/>
<PasswordInput
label='Password'
description='Passwords must be at least 8 characters long, contain at least one number, one uppercase letter, one lowercase letter, and one special character.'
// description='Passwords must be at least 8 characters long, contain at least one number, one uppercase letter, one lowercase letter, and one special character.'
placeholder='Your password'
required
mt='md'
@@ -184,9 +192,9 @@ export function HeaderModal({ type, toggle, login, register }: HeaderModalProps)
onSubmit={loginForm.onSubmit(async (values) => {
Cookies.set('remember', 'true', { expires: 365 });
if (values.remember) {
Cookies.set('email', values.email, { expires: 365 });
Cookies.set('username', values.username, { expires: 365 });
} else {
Cookies.remove('email');
Cookies.remove('username');
}
const success = await login(values);
if (success) {
@@ -194,7 +202,12 @@ export function HeaderModal({ type, toggle, login, register }: HeaderModalProps)
}
})}
>
<TextInput label='Email' placeholder='you@example.com' required {...loginForm.getInputProps('email')} />
<TextInput
label='Username'
placeholder='Your username'
required
{...loginForm.getInputProps('username')}
/>
<PasswordInput
label='Password'
placeholder='Your password'

View File

@@ -21,7 +21,7 @@ export default function HeaderUser({ user, profilePicture, logout }: HeaderUserP
<Avatar src={profilePicture ? URL.createObjectURL(profilePicture) : undefined} />
<div tabIndex={-1} style={{ flex: 1, userSelect: 'none' }}>
<Text size='sm' fw={500}>
{user.first_name} {user.last_name}
{user.firstName} {user.lastName}
</Text>
<Text c='dimmed' size='xs' style={{ textTransform: 'uppercase' }}>
{user.role}
@@ -62,7 +62,7 @@ export default function HeaderUser({ user, profilePicture, logout }: HeaderUserP
)}
</FileButton>
<Text ta='center' fz='lg' fw={500} mt='sm'>
{user.first_name} {user.last_name}
{user.firstName} {user.lastName}
</Text>
<Text ta='center' fz='sm' c='dimmed' style={{ textTransform: 'uppercase' }}>
{user.role}

View File

@@ -1,4 +1,4 @@
import { Autocomplete, Avatar, Box, Burger, Button, Group, Text } from '@mantine/core';
import { Avatar, Box, Burger, Button, Drawer, Group, Text } from '@mantine/core';
import { useDisclosure, useMediaQuery, useToggle } from '@mantine/hooks';
import classes from './Header.module.css';
import { HeaderModal } from '@components/Header/HeaderModal.tsx';
@@ -6,7 +6,8 @@ import { notifications } from '@mantine/notifications';
import { login, logout, register } from '@lib/account.ts';
import HeaderUser from '@components/Header/HeaderUser.tsx';
import { useUserContext } from '@components/context/UserContext.tsx';
import { Link } from 'react-router';
import { Link, matchPath, useLocation, useNavigate } from 'react-router';
import { AirportSearch } from '@components/AirportSearch.tsx';
// const links = [
// { link: '/', label: 'Map' },
@@ -14,11 +15,15 @@ import { Link } from 'react-router';
// { link: '/metars', label: 'Metars' }
// ];
const protectedPages = ['/administration', '/profile'];
export function Header() {
const { user, setUser } = useUserContext();
const [opened, { toggle }] = useDisclosure(false);
const [modalType, modalToggle] = useToggle([undefined, 'login', 'register', 'reset']);
const isMobile = useMediaQuery('(max-width: 768px)');
const { pathname } = useLocation();
const navigate = useNavigate();
// const [active, setActive] = useState(links[0].link);
// const navItems = links.map((link) => (
@@ -36,12 +41,12 @@ export function Header() {
// </a>
// ));
async function loginUser({ email, password }: { email: string; password: string }): Promise<boolean> {
const loginResponse = await login(email, password);
async function loginUser({ username, password }: { username: string; password: string }): Promise<boolean> {
const loginResponse = await login(username, password);
if (loginResponse) {
setUser(loginResponse);
notifications.show({
title: `Welcome back ${loginResponse.first_name}!`,
title: `Welcome back ${loginResponse.firstName}!`,
message: `You have been logged in.`,
color: 'green',
autoClose: 2000,
@@ -63,18 +68,25 @@ export function Header() {
async function logoutUser(): Promise<void> {
await logout();
setUser(undefined);
window.location.reload();
// See if the current page is a protected page
const isProtected = protectedPages.some((pattern) => matchPath(pattern, pathname));
if (isProtected) {
navigate('/', { replace: true });
}
}
async function registerUser({
firstName,
lastName,
username,
email,
password
}: {
firstName: string;
lastName: string;
email: string;
username: string;
email?: string;
password: string;
}): Promise<boolean> {
const id = notifications.show({
@@ -85,19 +97,20 @@ export function Header() {
withCloseButton: false
});
const registerResponse = await register({
first_name: firstName,
last_name: lastName,
firstName: firstName,
lastName: lastName,
username: username,
email: email,
password: password
});
if (registerResponse) {
const loginResponse = await login(email, password);
const loginResponse = await login(username, password);
if (loginResponse) {
setUser(loginResponse);
notifications.update({
id,
title: `Account created`,
message: `Welcome ${loginResponse.first_name}!`,
message: `Welcome ${loginResponse.firstName}!`,
color: 'green',
autoClose: 2000,
loading: false
@@ -133,7 +146,7 @@ export function Header() {
<Group justify='space-between' h='100%'>
<Group align='center' gap='xs'>
<Link to='/'>
<Avatar src='/logo.svg' alt='logo' onClick={toggle} />
<Avatar src='/logo.svg' alt='logo' />
</Link>
<Text size={'xl'}>Aviation Data</Text>
</Group>
@@ -142,7 +155,8 @@ export function Header() {
{/*</Group>*/}
{!isMobile && (
<Group align='center' gap='xs'>
<Autocomplete placeholder={'Enter airport name or ICAO'} limit={5} />
<AirportSearch />
{/*<Autocomplete placeholder={'Enter airport name or ICAO'} limit={5} />*/}
{user ? (
<HeaderUser user={user} profilePicture={undefined} logout={logoutUser} />
) : (
@@ -159,6 +173,21 @@ export function Header() {
</Group>
</header>
</Box>
<Drawer.Root
opened={opened}
onClose={toggle}
zIndex={1001}
padding="md"
size="40%"
position="right"
>
<Drawer.Overlay />
<Drawer.Content>
<Drawer.Body>
test
</Drawer.Body>
</Drawer.Content>
</Drawer.Root>
<HeaderModal type={modalType} toggle={modalToggle} login={loginUser} register={registerUser} />
</>
);

View File

@@ -0,0 +1,29 @@
import { AppShell } from '@mantine/core';
import { Outlet } from 'react-router';
import { Header } from '@components/Header';
import { Footer } from '@components/Footer';
export function MainLayout() {
return (
<AppShell padding={0} mih={'100dvh'}>
<AppShell.Header>
<Header />
</AppShell.Header>
<AppShell.Main p={0} style={{ display: 'flex', minHeight: 0 }}>
<div
style={{
display: 'flex',
flexDirection: 'column',
flex: 1,
minHeight: 0
}}
>
<Outlet />
</div>
</AppShell.Main>
<AppShell.Footer>
<Footer />
</AppShell.Footer>
</AppShell>
);
}

View File

@@ -1,4 +1,3 @@
import { Header } from '@components/Header';
import { useUserContext } from '@components/context/UserContext.tsx';
import { NotFound } from '@components/NotFound';
@@ -11,8 +10,7 @@ export function Profile() {
return (
<>
<Header />
Todo: profile {user?.first_name}
Todo: profile {user?.firstName}
</>
);
}

View File

@@ -5,12 +5,16 @@ interface UserContextType {
user?: User;
setUser: (user: User | undefined) => void;
loading: boolean;
favorites: string[];
toggleFavorite: (icao: string) => void;
}
export const UserContext = createContext<UserContextType>({
user: undefined,
setUser: () => {},
loading: true
loading: true,
favorites: [],
toggleFavorite: () => {}
});
export function useUserContext(): UserContextType {

View File

@@ -1,6 +1,6 @@
import { ReactNode, useEffect, useState } from 'react';
import { UserContext } from './UserContext.tsx';
import { profile } from '@lib/account.ts';
import { addFavorite, getFavorites, profile, removeFavorite } from '@lib/account.ts';
import { User } from '@lib/account.types.ts';
import { Center, Loader } from '@mantine/core';
import Cookies from 'js-cookie';
@@ -9,8 +9,23 @@ const sessionExpirationName = 'session_expiration';
export function UserProvider({ children }: { children: ReactNode }) {
const [user, setUser] = useState<User | undefined>(undefined);
const [favorites, setFavorites] = useState<string[]>([]);
const [loading, setLoading] = useState(true);
async function toggleFavorite(icao: string) {
setFavorites((prev) => {
const isFav = prev.includes(icao);
const next = isFav ? prev.filter((i) => i !== icao) : [...prev, icao];
(isFav ? removeFavorite(icao) : addFavorite(icao)).catch((err) => {
console.error('Sync failed, rolling back', err);
setFavorites(prev);
});
return next;
});
}
useEffect(() => {
const sessionExpiration = Cookies.get(sessionExpirationName);
@@ -35,8 +50,16 @@ export function UserProvider({ children }: { children: ReactNode }) {
}
}, []);
useEffect(() => {
if (user != undefined) {
getFavorites().then((f) => {
setFavorites(f);
});
}
}, [user]);
return (
<UserContext.Provider value={{ user, setUser, loading }}>
<UserContext.Provider value={{ user, setUser, loading, favorites, toggleFavorite }}>
{loading ? (
<Center style={{ height: '100vh' }}>
<Loader size='xl' />

Some files were not shown because too many files have changed in this diff Show More