Updated airport data, fixed loader/header

This commit is contained in:
2023-12-21 14:19:17 -05:00
parent 8438acc68b
commit 0b2ef94b99
26 changed files with 472068 additions and 62093 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -1,63 +0,0 @@
import pandas as pd
from datetime import date
import json
# Load the airports.csv file from the web
url = 'https://davidmegginson.github.io/ourairports-data/airports.csv'
df = pd.read_csv(url, index_col=0)
# convert the dataframe to a dictionary
airports = df.to_dict('index')
formated_airports = {}
for airport in airports:
category = airports[airport]['type']
if pd.isnull(category) or category == 'nan' or category == 'NAN':
category = 'UNKNOWN'
elevation = airports[airport]['elevation_ft']
if pd.isnull(elevation) or elevation == 'nan' or elevation == 'NAN':
elevation = 0
country = airports[airport]['iso_country']
if pd.isnull(country) or country == 'nan' or country == 'NAN':
country = 'UNKNOWN'
region = airports[airport]['iso_region']
if pd.isnull(region) or region == 'nan' or region == 'NAN':
region = 'UNKNOWN'
municipality = airports[airport]['municipality']
if pd.isnull(municipality) or municipality == 'nan' or municipality == 'NAN':
municipality = 'UNKNOWN'
iata = airports[airport]['iata_code']
if pd.isnull(iata) or iata == 'nan' or iata == 'NAN':
iata = ''
local = airports[airport]['local_code']
if pd.isnull(local) or local == 'nan' or local == 'NAN':
local = ''
formated_airports[airport] = {
'icao': airports[airport]['ident'],
'category': category,
'name': airports[airport]['name'],
'elevation_ft': elevation,
'iso_country': country,
'iso_region': region,
'municipality': municipality,
'iata_code': iata,
'local_code': local,
'latitude': airports[airport]['latitude_deg'],
'longitude': airports[airport]['longitude_deg']
}
# convert the dictionary to a list of dictionaries
formated_airports = list(formated_airports.values())
# convert the list of dictionaries to a json file
today = date.today()
date = today.strftime("%Y-%m-%d")
with open(f'airports_{date}.json', 'wb') as file:
file.write(json.dumps(formated_airports).encode('utf-8'))

File diff suppressed because one or more lines are too long

471580
data/airports_2023-12-21.json Normal file

File diff suppressed because it is too large Load Diff

View File

View File

@@ -10,23 +10,41 @@ use log::error;
use postgis_diesel::types::*; use postgis_diesel::types::*;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
pub struct Runway {
pub id: String,
pub length_ft: f32,
pub width_ft: f32,
pub surface: String,
}
#[derive(Serialize, Deserialize)]
pub struct Frequency {
pub id: String,
pub frequency_mhz: f32,
}
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
pub struct Airport { pub struct Airport {
pub icao: String, pub icao: String,
pub category: AirportCategory, #[serde(skip_serializing_if = "Option::is_none")]
pub iata: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub local: Option<String>,
pub name: String, pub name: String,
pub elevation_ft: f32, pub category: AirportCategory,
pub iso_country: String, pub iso_country: String,
pub iso_region: String, pub iso_region: String,
pub municipality: String, pub municipality: String,
#[serde(skip_serializing_if = "Option::is_none")] pub elevation_ft: f32,
pub iata_code: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub local_code: Option<String>,
pub latitude: f64, pub latitude: f64,
pub longitude: f64, pub longitude: f64,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub has_tower: Option<bool>, pub has_tower: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub has_beacon: Option<bool>,
pub runways: Vec<Runway>,
pub frequencies: Vec<Frequency>,
} }
impl Into<QueryAirport> for Airport { impl Into<QueryAirport> for Airport {

View File

@@ -22,7 +22,7 @@ async fn main() -> std::io::Result<()> {
dotenv().ok(); dotenv().ok();
env_logger::init_from_env(env_logger::Env::default().filter_or("RUST_LOG", "warn,service=info")); env_logger::init_from_env(env_logger::Env::default().filter_or("RUST_LOG", "warn,service=info"));
db::init(); db::init();
scheduler::update_airports(); // scheduler::update_airports();
let host = env::var("SERVICE_HOST").unwrap_or("localhost".to_string()); let host = env::var("SERVICE_HOST").unwrap_or("localhost".to_string());
let port = env::var("SERVICE_PORT").unwrap_or("5000".to_string()); let port = env::var("SERVICE_PORT").unwrap_or("5000".to_string());

View File

@@ -225,31 +225,50 @@ impl Metar {
// Wind Direction and Speed // Wind Direction and Speed
let wind_re = regex::Regex::new(r"^(?:[0-9]{3}|VRB)[0-9]{2}(?:KT|MPS)$").unwrap(); 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_gust_re = regex::Regex::new(r"^(?:[0-9]{3}|VRB)[0-9]{2}G[0-9]{2}(?:KT|MPS)$").unwrap();
if !metar_parts.is_empty() && wind_re.is_match(metar_parts[0]) { // Handle input error where there is a space between the numbers and units
let wind = metar_parts[0]; let mut value: Option<String> = None;
if metar_parts.len() >= 2 && metar_parts[0].len() == 5 && (metar_parts[1] == "KT" || metar_parts[1] == "MPS") {
value = Some(format!("{}{}", metar_parts[0], metar_parts[1]));
metar_parts.remove(0);
metar_parts.remove(0);
} else if metar_parts.len() >= 2 && metar_parts[0].len() == 7 && metar_parts[0].contains("G") && (metar_parts[1] == "KT" || metar_parts[1] == "MPS") {
value = Some(format!("{}{}", metar_parts[0], metar_parts[1]));
metar_parts.remove(0);
metar_parts.remove(0);
} else if !metar_parts.is_empty() && wind_re.is_match(metar_parts[0]) {
value = Some(metar_parts[0].to_string());
metar_parts.remove(0); metar_parts.remove(0);
let wind_dir_degrees = &wind[0..3];
metar.wind_dir_degrees = Some(wind_dir_degrees.to_string());
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();
}
metar.wind_speed_kt = Some(wind_speed_kt.parse::<f64>().unwrap());
} else if !metar_parts.is_empty() && wind_gust_re.is_match(metar_parts[0]) { } else if !metar_parts.is_empty() && wind_gust_re.is_match(metar_parts[0]) {
let wind = metar_parts[0]; value = Some(metar_parts[0].to_string());
metar_parts.remove(0); metar_parts.remove(0);
let wind_dir_degrees = &wind[0..3]; }
metar.wind_dir_degrees = Some(wind_dir_degrees.to_string());
let mut wind_speed_kt = wind[3..5].to_string(); match value {
let mut wind_gust_kt = wind[6..8].to_string(); Some(wind) => {
// Convert m/s to kt if wind_re.is_match(&wind) {
if wind.len() == 9 { let wind_dir_degrees = &wind[0..3];
wind_speed_kt = (wind_speed_kt.parse::<f64>().unwrap() * 1.94384).to_string(); metar.wind_dir_degrees = Some(wind_dir_degrees.to_string());
wind_gust_kt = (wind_gust_kt.parse::<f64>().unwrap() * 1.94384).to_string(); let mut wind_speed_kt = wind[3..5].to_string();
} // Convert m/s to kt
metar.wind_speed_kt = Some(wind_speed_kt.parse::<f64>().unwrap()); if wind.len() == 8 {
metar.wind_gust_kt = Some(wind_gust_kt.parse::<f64>().unwrap()); wind_speed_kt = (wind_speed_kt.parse::<f64>().unwrap() * 1.94384).to_string();
}
metar.wind_speed_kt = Some(wind_speed_kt.parse::<f64>().unwrap());
} 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());
let mut wind_speed_kt = wind[3..5].to_string();
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();
}
metar.wind_speed_kt = Some(wind_speed_kt.parse::<f64>().unwrap());
metar.wind_gust_kt = Some(wind_gust_kt.parse::<f64>().unwrap());
}
},
None => {}
} }
// Variable Wind Direction // Variable Wind Direction
@@ -516,17 +535,18 @@ impl Metar {
} }
None => 5.0 // Assume VFR if no visibility is present None => 5.0 // Assume VFR if no visibility is present
}; };
// Ceiling is the lowest cloud base that is BKN or OVC
let ceiling = match metar.sky_condition.first() { let ceiling = match metar.sky_condition.first() {
Some(s) => { Some(s) => {
if s.sky_cover == "CLR" || s.sky_cover == "SKC" || s.sky_cover == "NSC" || s.sky_cover == "NCD" { if s.sky_cover == "VV" {
3000.0
} else if s.sky_cover == "VV" {
0.0 0.0
} else { } else if s.sky_cover == "BKN" || s.sky_cover == "OVC" {
match s.cloud_base_ft_agl { match s.cloud_base_ft_agl {
Some(c) => c as f64, Some(c) => c as f64,
None => 0.0 None => 0.0
} }
} else {
3000.0 // Assume VFR if no BKN or OVC sky condition is present
} }
}, },
None => 3000.0 // Assume VFR if no sky condition is present None => 3000.0 // Assume VFR if no sky condition is present
@@ -564,7 +584,7 @@ impl Metar {
return missing_metar_icaos; return missing_metar_icaos;
} }
async fn get_remote_metars(icaos: Vec<String>) -> Vec<Metar> { async fn get_remote_metars(icaos: Vec<String>) -> Result<Vec<Metar>, ServiceError> {
let gov_api_url = std::env::var("GOV_API_URL").expect("GOV_API_URL must be set"); let gov_api_url = std::env::var("GOV_API_URL").expect("GOV_API_URL must be set");
// Query the remote API for the missing METAR data 10 at a time // 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 icao_chunks = icaos.chunks(10).map(|chunk| chunk.join(",")).collect::<Vec<String>>();
@@ -572,54 +592,27 @@ impl Metar {
for icao_chunk in icao_chunks { for icao_chunk in icao_chunks {
let url = format!("{}/metar.php?ids={}", gov_api_url, icao_chunk); let url = format!("{}/metar.php?ids={}", gov_api_url, icao_chunk);
let mut m = match reqwest::get(url).await { let mut m = match reqwest::get(url).await {
Ok(r) => match r.text().await { Ok(r) => {
Ok(r) => { // Check if the status code is 200
let metar_chunk = r.trim().split("\n").filter(|m| !m.trim().is_empty()).collect(); if r.status() != 200 {
match Metar::parse(metar_chunk) { return Err(ServiceError::new(500, format!("Unable to get METAR request: {}", r.status())));
Ok(m) => m, }
Err(err) => { match r.text().await {
warn!("{}", err); Ok(r) => {
return metars; let metar_chunk = r.trim().split("\n").filter(|m| !m.trim().is_empty()).collect();
match Metar::parse(metar_chunk) {
Ok(m) => m,
Err(err) => return Err(err)
} }
} },
}, Err(err) => return Err(ServiceError::new(500, format!("Unable to parse METAR request: {}", err)))
Err(err) => {
warn!("Unable to parse METAR request: {}", err);
return metars;
} }
}, },
Err(err) => { Err(err) => return Err(ServiceError::new(500, format!("Unable to get METAR request: {}", err)))
warn!("Unable to get METAR request: {}", err);
return metars;
}
}; };
metars.append(&mut m); metars.append(&mut m);
} }
return Ok(metars);
let icaos_string = icaos.join(",");
let url = format!("{}/metar.php?ids={}", gov_api_url, icaos_string);
match reqwest::get(url).await {
Ok(r) => match r.text().await {
Ok(r) => {
let metar_strings = r.trim().split("\n").filter(|m| !m.trim().is_empty()).collect();
match Metar::parse(metar_strings) {
Ok(m) => m,
Err(err) => {
warn!("{}", err);
return metars;
}
}
},
Err(err) => {
warn!("Unable to parse METAR request: {}", err);
return metars;
}
},
Err(err) => {
warn!("Unable to get METAR request: {}", err);
return metars;
}
}
} }
fn from_query(query_metars: Vec<QueryMetar>) -> Vec<Self> { fn from_query(query_metars: Vec<QueryMetar>) -> Vec<Self> {
@@ -671,7 +664,14 @@ impl Metar {
Err(_) => {} Err(_) => {}
} }
}); });
let mut missing_metars = Self::get_remote_metars(missing_icaos_string).await; let missing_result = Self::get_remote_metars(missing_icaos_string).await;
let mut missing_metars = match missing_result {
Ok(m) => m,
Err(err) => {
warn!("Unable to get remote METAR data; {}", err);
vec![]
}
};
if missing_metars.len() > 0 { if missing_metars.len() > 0 {
let insert_metars = Self::to_insert(&missing_metars); let insert_metars = Self::to_insert(&missing_metars);
match InsertMetar::insert(&insert_metars) { match InsertMetar::insert(&insert_metars) {

View File

@@ -6,6 +6,8 @@ use crate::metars::Metar;
pub fn update_airports() { pub fn update_airports() {
tokio::spawn(async { tokio::spawn(async {
let mut airports: Vec<QueryAirport> = vec![];
let limit = 100;
loop { loop {
debug!("METAR update start"); debug!("METAR update start");
let total = match QueryAirport::get_count(&QueryFilters::default()) { let total = match QueryAirport::get_count(&QueryFilters::default()) {
@@ -15,17 +17,19 @@ pub fn update_airports() {
break break
} }
}; };
let limit = 50; if total != airports.len() as i64 {
let pages = ((total as f32) / (if limit <= 0 { 1 } else { limit} as f32)).ceil() as i32; debug!("{} cached airports, expected {}", airports.len(), total);
let mut airports: Vec<QueryAirport> = vec![]; airports = vec![];
for page in 1..(pages + 1) { let pages = ((total as f32) / (if limit <= 0 { 1 } else { limit} as f32)).ceil() as i32;
match QueryAirport::get_all(&QueryFilters::default(), limit, page) { for page in 1..(pages + 1) {
Ok(mut a) => { match QueryAirport::get_all(&QueryFilters::default(), limit, page) {
airports.append(&mut a) Ok(mut a) => {
}, airports.append(&mut a)
Err(err) => { },
warn!("{}", err); Err(err) => {
break warn!("{}", err);
break
}
} }
} }
} }
@@ -36,6 +40,7 @@ pub fn update_airports() {
let mut observation_time = chrono::Utc::now().timestamp(); let mut observation_time = chrono::Utc::now().timestamp();
if peekable.peek().is_none() { if peekable.peek().is_none() {
debug!("No airports to update, sleeping for 1 hour");
sleep(Duration::from_secs(3600)).await; sleep(Duration::from_secs(3600)).await;
continue; continue;
} }
@@ -52,12 +57,13 @@ pub fn update_airports() {
observation_time = metar.observation_time.timestamp(); observation_time = metar.observation_time.timestamp();
} }
} }
sleep(Duration::from_millis(100)).await;
}, },
Err(err) => { Err(err) => {
warn!("{}", err); warn!("{}", err);
} }
} }
// Sleep for 100ms between chunks to avoid rate limiting
sleep(Duration::from_millis(100)).await;
} }
debug!("METAR update complete"); debug!("METAR update complete");
// Sleep until the earliest observation time is 1 hour old // Sleep until the earliest observation time is 1 hour old

View File

@@ -5,18 +5,14 @@ const nextConfig = {
eslint: { eslint: {
ignoreDuringBuilds: true ignoreDuringBuilds: true
}, },
// webpackDevMiddleware: (config) => {
// config.watchOptions = {
// poll: 1000,
// aggregateTimeout: 300
// };
// return config;
// },
publicRuntimeConfig: { publicRuntimeConfig: {
// remove private variables from processEnv // remove private variables from processEnv
processEnv: Object.fromEntries(Object.entries(process.env).filter(([key]) => key.includes('NEXT_PUBLIC_'))) processEnv: Object.fromEntries(Object.entries(process.env).filter(([key]) => key.includes('NEXT_PUBLIC_')))
}, },
output: 'standalone' output: 'standalone',
experimental: {
optimizePackageImports: ['@mantine/core', '@mantine/hooks'],
},
}; };
module.exports = nextConfig; module.exports = nextConfig;

9
ui/package-lock.json generated
View File

@@ -38,7 +38,8 @@
"eslint-plugin-prettier": "^5.1.0", "eslint-plugin-prettier": "^5.1.0",
"postcss": "^8.4.32", "postcss": "^8.4.32",
"postcss-import": "^15.1.0", "postcss-import": "^15.1.0",
"postcss-preset-mantine": "^1.12.0", "postcss-preset-mantine": "^1.12.1",
"postcss-simple-vars": "^7.0.1",
"prettier": "^3.1.1", "prettier": "^3.1.1",
"typescript": "5.3.3" "typescript": "5.3.3"
} }
@@ -4034,9 +4035,9 @@
} }
}, },
"node_modules/postcss-preset-mantine": { "node_modules/postcss-preset-mantine": {
"version": "1.12.0", "version": "1.12.1",
"resolved": "https://registry.npmjs.org/postcss-preset-mantine/-/postcss-preset-mantine-1.12.0.tgz", "resolved": "https://registry.npmjs.org/postcss-preset-mantine/-/postcss-preset-mantine-1.12.1.tgz",
"integrity": "sha512-WLsejZoNtsrpOEi/CItn98e+4NpgT/Av28XWfY0CqiWgd2NDOOxtEUNdPGtB33pGLwaV8FrhTpIhAIO8palTOw==", "integrity": "sha512-N1biscmlvJHYPWN6znrlFre80wh9baAaMETfERn8acQJykioGYmHIJLpQSwUSxqq/PG8QbayUyOnHgBV/tsZyA==",
"dev": true, "dev": true,
"dependencies": { "dependencies": {
"postcss-mixins": "^9.0.4", "postcss-mixins": "^9.0.4",

View File

@@ -39,7 +39,8 @@
"eslint-plugin-prettier": "^5.1.0", "eslint-plugin-prettier": "^5.1.0",
"postcss": "^8.4.32", "postcss": "^8.4.32",
"postcss-import": "^15.1.0", "postcss-import": "^15.1.0",
"postcss-preset-mantine": "^1.12.0", "postcss-preset-mantine": "^1.12.1",
"postcss-simple-vars": "^7.0.1",
"prettier": "^3.1.1", "prettier": "^3.1.1",
"typescript": "5.3.3" "typescript": "5.3.3"
} }

View File

@@ -1,6 +1,15 @@
module.exports = { module.exports = {
plugins: { plugins: {
'postcss-preset-mantine': {}, 'postcss-preset-mantine': {},
'postcss-simple-vars': {
variables: {
'mantine-breakpoint-xs': '36em',
'mantine-breakpoint-sm': '48em',
'mantine-breakpoint-md': '62em',
'mantine-breakpoint-lg': '75em',
'mantine-breakpoint-xl': '88em',
},
},
'postcss-import': {}, 'postcss-import': {},
autoprefixer: {} autoprefixer: {}
} }

7
ui/public/icons/VFR.svg Normal file
View File

@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg id="svg874" width="185.96mm" height="185.96mm" version="1.1" viewBox="0 0 185.96 185.96" xmlns="http://www.w3.org/2000/svg">
<circle id="path1419" cx="92.99" cy="92.983" r="92.982" fill="#28a745"/>
<g id="text1423" fill="#fff" stroke-width="13.795" style="font-feature-settings:normal;font-variant-caps:normal;font-variant-ligatures:normal;font-variant-numeric:normal" aria-label="V">
<path id="path821" d="m120.94 45.222h17.819l-36.787 105.05h-18.106l-36.644-105.05h17.675l21.914 65.312q1.7244 4.6703 3.6644 12.071 1.94 7.3288 2.5148 10.921 0.93406-5.4606 2.874-12.646 1.94-7.1851 3.1614-10.634z" fill="#fff" stroke-width="13.795"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 695 B

12
ui/public/icons/ifr.svg Normal file
View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="100%" height="100%" viewBox="0 0 128 128" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" xmlns:serif="http://www.serif.com/" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2;">
<g transform="matrix(2.5585,0,0,2.52891,-36.3432,-32.3701)">
<ellipse cx="39.22" cy="38.107" rx="25.015" ry="25.307" style="fill:rgb(255,0,0);"/>
</g>
<g transform="matrix(130.653,0,0,130.653,45.627,110.762)">
<g transform="matrix(1,0,0,1,0.277832,0)">
</g>
<text x="0px" y="0px" style="font-family:'ArialMT', 'Arial', sans-serif;font-size:1px;fill:white;">I</text>
</g>
</svg>

After

Width:  |  Height:  |  Size: 871 B

12
ui/public/icons/lifr.svg Normal file
View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="100%" height="100%" viewBox="0 0 128 128" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" xmlns:serif="http://www.serif.com/" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2;">
<g transform="matrix(2.5585,0,0,2.52891,-36.3432,-32.3701)">
<ellipse cx="39.22" cy="38.107" rx="25.015" ry="25.307" style="fill:rgb(128,0,128);"/>
</g>
<g transform="matrix(128.435,0,0,128.435,25.8707,109.968)">
<g transform="matrix(1,0,0,1,0.556152,0)">
</g>
<text x="0px" y="0px" style="font-family:'ArialMT', 'Arial', sans-serif;font-size:1px;fill:white;">L</text>
</g>
</svg>

After

Width:  |  Height:  |  Size: 874 B

12
ui/public/icons/mvfr.svg Normal file
View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="100%" height="100%" viewBox="0 0 128 128" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" xmlns:serif="http://www.serif.com/" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2;">
<g transform="matrix(2.5585,0,0,2.52891,-36.3432,-32.3701)">
<ellipse cx="39.22" cy="38.107" rx="25.015" ry="25.307" style="fill:rgb(0,0,255);"/>
</g>
<g transform="matrix(238.636,0,0,238.636,-4483.2,-6772.13)">
<g transform="matrix(0.50957,0,0,0.50957,19.2676,28.829)">
</g>
<text x="18.843px" y="28.829px" style="font-family:'ArialMT', 'Arial', sans-serif;font-size:0.51px;fill:white;">M</text>
</g>
</svg>

After

Width:  |  Height:  |  Size: 902 B

12
ui/public/icons/unkn.svg Normal file
View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="100%" height="100%" viewBox="0 0 128 128" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" xmlns:serif="http://www.serif.com/" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2;">
<g transform="matrix(2.5585,0,0,2.52891,-36.3432,-32.3701)">
<ellipse cx="39.22" cy="38.107" rx="25.015" ry="25.307" style="fill:rgb(62,62,62);"/>
</g>
<g transform="matrix(238.636,0,0,238.636,-4476.43,-6772.87)">
<g transform="matrix(0.50957,0,0,0.50957,19.2111,28.829)">
</g>
<text x="18.843px" y="28.829px" style="font-family:'ArialMT', 'Arial', sans-serif;font-size:0.51px;fill:white;">U</text>
</g>
</svg>

After

Width:  |  Height:  |  Size: 904 B

View File

@@ -1,34 +1,32 @@
import React from 'react'; import React from 'react';
import RecoilRootWrapper from '@app/recoil-root-wrapper'; import RecoilRootWrapper from '@app/recoil-root-wrapper';
import Header from '@/components/Header';
import { Inter } from 'next/font/google';
import { MantineProvider } from '@mantine/core'; import { MantineProvider } from '@mantine/core';
import { ModalsProvider } from '@mantine/modals'; import { ModalsProvider } from '@mantine/modals';
import 'styles/globals.css'; import 'styles/globals.css';
import 'styles/leaflet.css'; import 'styles/leaflet.css';
import '@mantine/core/styles.css'; import '@mantine/core/styles.css';
import { Notifications } from '@mantine/notifications'; import { Notifications } from '@mantine/notifications';
import Loader from '@/components/Loader';
export const metadata = { export const metadata = {
title: 'Aviation Weather', title: 'Aviation Weather',
description: '' description: ''
}; };
const inter = Inter({ subsets: ['latin'] });
export default function RootLayout({ children }: { children: React.ReactNode }) { export default function RootLayout({ children }: { children: React.ReactNode }) {
return ( return (
<html lang='en' className='h-full bg-white'> <html lang='en'>
<head> <head>
<title>Aviation Weather</title> <title>Aviation Weather</title>
</head> </head>
<body className={`${inter.className} wrapper h-full`}> <body>
<MantineProvider> <MantineProvider>
<Notifications /> <Notifications />
<ModalsProvider> <ModalsProvider>
<RecoilRootWrapper> <RecoilRootWrapper>
<Header /> <Loader>
{children} {children}
</Loader>
</RecoilRootWrapper> </RecoilRootWrapper>
</ModalsProvider> </ModalsProvider>
</MantineProvider> </MantineProvider>

View File

@@ -1,7 +1,5 @@
'use client'; 'use client';
import { login, register, refreshLoggedIn } from '@/api/auth';
import { User } from '@/api/auth.types';
import { import {
Modal, Modal,
Container, Container,
@@ -16,16 +14,15 @@ import {
Text Text
} from '@mantine/core'; } from '@mantine/core';
import { useForm } from '@mantine/form'; import { useForm } from '@mantine/form';
import { notifications } from '@mantine/notifications';
interface HeaderModalProps { interface HeaderModalProps {
type?: string; type?: string;
toggle: any; toggle: any;
setUser: (user: User) => void; login: ({ email, password }: { email: string, password: string }) => Promise<boolean>;
setRefreshId: (id: NodeJS.Timeout) => void; register: ({ firstName, lastName, email, password }: { firstName: string, lastName: string, email: string, password: string }) => Promise<boolean>;
} }
export function HeaderModal({ type, toggle, setUser, setRefreshId }: HeaderModalProps) { export function HeaderModal({ type, toggle, login, register }: HeaderModalProps) {
function passwordValidator(value: string) { function passwordValidator(value: string) {
if (value.trim().length < 10) { if (value.trim().length < 10) {
return 'Password must be at least 10 characters'; return 'Password must be at least 10 characters';
@@ -129,52 +126,9 @@ export function HeaderModal({ type, toggle, setUser, setRefreshId }: HeaderModal
<Paper withBorder shadow='md' p={30} mt={30} radius='md'> <Paper withBorder shadow='md' p={30} mt={30} radius='md'>
<form <form
onSubmit={registerForm.onSubmit(async (values) => { onSubmit={registerForm.onSubmit(async (values) => {
const id = notifications.show({ const success = await register(values);
loading: true, if (success) {
title: `Creating account`, onClose();
message: `Please wait...`,
autoClose: false,
withCloseButton: false
});
const registerResponse = await register({
first_name: values.firstName,
last_name: values.lastName,
email: values.email,
password: values.password
});
if (registerResponse) {
const loginResponse = await login(values.email, values.password);
if (loginResponse) {
setUser(loginResponse.user);
setRefreshId(refreshLoggedIn());
onClose();
notifications.update({
id,
title: `Account created`,
message: `Welcome ${loginResponse.user.first_name}!`,
color: 'green',
autoClose: 2000,
loading: false
});
} else {
notifications.update({
id,
title: `Unable to Login`,
message: `Please try again.`,
color: 'red',
autoClose: 2000,
loading: false
});
}
} else {
notifications.update({
id,
title: `Unable to Register`,
message: `Please try again.`,
color: 'error',
autoClose: 2000,
loading: false
});
} }
})} })}
> >
@@ -219,18 +173,9 @@ export function HeaderModal({ type, toggle, setUser, setRefreshId }: HeaderModal
<Paper withBorder shadow='md' p={30} mt={30} radius='md'> <Paper withBorder shadow='md' p={30} mt={30} radius='md'>
<form <form
onSubmit={loginForm.onSubmit(async (values) => { onSubmit={loginForm.onSubmit(async (values) => {
const response = await login(values.email, values.password); const success = await login(values);
if (response) { if (success) {
setUser(response.user);
setRefreshId(refreshLoggedIn());
onClose(); onClose();
} else {
notifications.show({
title: `Unable to Login`,
message: `Please try again.`,
color: 'red',
autoClose: 2000
});
} }
})} })}
> >

View File

@@ -1,55 +1,31 @@
'use client'; 'use client';
import Link from 'next/link'; import Link from 'next/link';
import { useEffect, useState } from 'react'; import { useState } from 'react';
import { getAirport, getAirports } from '@/api/airport'; import { getAirport, getAirports } from '@/api/airport';
import { Autocomplete, Avatar, Button, Card, FileButton, Grid, Group, Menu, Text, UnstyledButton } from '@mantine/core'; import { Autocomplete, Avatar, Button, Card, FileButton, Grid, Group, Menu, Text, UnstyledButton } from '@mantine/core';
import './header.css'; import './header.css';
import { refresh, refreshLoggedIn, logout } from '@/api/auth'; import { SetterOrUpdater, useRecoilState } from 'recoil';
import Cookies from 'js-cookie'; import { setPicture } from '@/api/users';
import { useRecoilState } from 'recoil';
import { userState } from '@/state/auth';
import { getFavorites, getPicture, setPicture } from '@/api/users';
import { useToggle } from '@mantine/hooks'; import { useToggle } from '@mantine/hooks';
import { HeaderModal } from './HeaderModal'; import { HeaderModal } from './HeaderModal';
import { favoritesState } from '@/state/user'; import { coordinatesState } from '@/state/map';
import { coordinatesState, zoomState } from '@/state/map'; import { User } from '@/api/auth.types';
export default function Header() { interface HeaderProps {
const [loading, setLoading] = useState(true); user: User | undefined;
profilePicture: File | undefined;
setProfilePicture: SetterOrUpdater<File | undefined>;
login: ({ email, password }: { email: string, password: string }) => Promise<boolean>;
logout: () => Promise<void>;
register: ({ firstName, lastName, email, password }: { firstName: string, lastName: string, email: string, password: string }) => Promise<boolean>;
}
export default function Header({ user, profilePicture, setProfilePicture, login, logout, register }: HeaderProps) {
const [searchValue, setSearchValue] = useState(''); const [searchValue, setSearchValue] = useState('');
const [airports, setAirports] = useState<{ key: string; value: string; label: string }[]>([]); const [airports, setAirports] = useState<{ key: string; value: string; label: string }[]>([]);
const [modalType, toggle] = useToggle([undefined, 'login', 'register', 'reset']); const [modalType, toggle] = useToggle([undefined, 'login', 'register', 'reset']);
const [user, setUser] = useRecoilState(userState); const [_, setCoordinates] = useRecoilState(coordinatesState);
const [favorites, setFavorites] = useRecoilState(favoritesState);
const [refreshId, setRefreshId] = useState<NodeJS.Timeout | undefined>(undefined);
const [profilePicture, setProfilePicture] = useState<File | null>(null);
const [coordinates, setCoordinates] = useRecoilState(coordinatesState);
const [zoom, setZoom] = useRecoilState(zoomState);
useEffect(() => {
if (!user || !Cookies.get('logged_in')) {
refresh().then((response) => {
if (response) {
setRefreshId(refreshLoggedIn());
setUser(response.user);
getFavorites().then((response) => {
if (response) {
setFavorites(response);
}
});
if (response.user.profile_picture) {
getPicture().then((response) => {
if (response) {
setProfilePicture(response as File);
}
});
}
}
});
}
setLoading(false);
}, [user]);
async function onChange(value: string) { async function onChange(value: string) {
setSearchValue(value); setSearchValue(value);
@@ -91,160 +67,130 @@ export default function Header() {
</div> </div>
</div> </div>
<UserSection <UserSection
user={user}
profilePicture={profilePicture} profilePicture={profilePicture}
setProfilePicture={setProfilePicture} setProfilePicture={setProfilePicture}
toggle={toggle} toggle={toggle}
setFavorites={setFavorites} logout={logout}
refreshId={refreshId}
loading={loading}
/> />
</nav> </nav>
<HeaderModal <HeaderModal
type={modalType} type={modalType}
toggle={toggle} toggle={toggle}
setUser={(u) => { login={login}
setUser(u); register={register}
getFavorites().then((response) => {
if (response) {
setFavorites(response);
}
});
if (u.profile_picture) {
getPicture().then((response) => {
if (response) {
setProfilePicture(response as File);
}
});
}
}}
setRefreshId={setRefreshId}
/> />
</> </>
); );
} }
interface UserSectionProps { interface UserSectionProps {
profilePicture: File | null; user: User | undefined;
setProfilePicture: (picture: File | null) => void; profilePicture: File | undefined;
setProfilePicture: SetterOrUpdater<File | undefined>;
toggle: (type: string) => void; toggle: (type: string) => void;
setFavorites: (favorites: string[]) => void; logout: () => Promise<void>;
refreshId: NodeJS.Timeout | undefined;
loading: boolean;
} }
function UserSection({ profilePicture, setProfilePicture, setFavorites, refreshId, toggle, loading }: UserSectionProps) { function UserSection({ user, profilePicture, setProfilePicture, logout, toggle }: UserSectionProps) {
const [user, setUser] = useRecoilState(userState);
return ( return (
<div className='user-section'> <div className='user-section'>
{loading ? ( <>
<></> {user ? (
) : ( <Menu shadow='md' width={200} openDelay={100} closeDelay={400}>
<> <Menu.Target>
{user ? ( <UnstyledButton className='user user-button'>
<Menu shadow='md' width={200} openDelay={100} closeDelay={400}> <Group>
<Menu.Target> <Avatar src={profilePicture ? URL.createObjectURL(profilePicture) : undefined} />
<UnstyledButton className='user user-button'> <div style={{ flex: 1 }}>
<Group> <Text size='sm' fw={500}>
<Avatar src={profilePicture ? URL.createObjectURL(profilePicture) : undefined} /> {user.first_name} {user.last_name}
<div style={{ flex: 1 }}> </Text>
<Text size='sm' fw={500}> <Text c='dimmed' size='xs' style={{ textTransform: 'uppercase' }}>
{user.first_name} {user.last_name} {user.role}
</Text> </Text>
<Text c='dimmed' size='xs' style={{ textTransform: 'uppercase' }}> </div>
{user.role} </Group>
</Text> </UnstyledButton>
</div> </Menu.Target>
</Group> <Menu.Dropdown p={0}>
</UnstyledButton> <Card>
</Menu.Target> <Card.Section h={140} style={{ backgroundColor: '#4481e3' }} />
<Menu.Dropdown p={0}> <FileButton
<Card> onChange={(payload) => {
<Card.Section h={140} style={{ backgroundColor: '#4481e3' }} /> if (payload) {
<FileButton setPicture(payload).then((response) => {
onChange={(payload) => { if (response) {
if (payload) { setProfilePicture(payload);
setPicture(payload).then((response) => { }
if (response) { });
setProfilePicture(payload); }
} }}
}); accept='image/png,image/jpeg,image/jpg'
} multiple={false}
}} >
accept='image/png,image/jpeg,image/jpg' {(props) => (
multiple={false} <Avatar
> {...props}
{(props) => ( component='button'
<Avatar size={80}
{...props} radius={80}
component='button' mx={'auto'}
size={80} mt={-30}
radius={80} style={{ cursor: 'pointer' }}
mx={'auto'} bg={profilePicture ? 'transparent' : 'white'}
mt={-30} src={profilePicture ? URL.createObjectURL(profilePicture) : undefined}
style={{ cursor: 'pointer' }} />
bg={profilePicture ? 'transparent' : 'white'} )}
src={profilePicture ? URL.createObjectURL(profilePicture) : undefined} </FileButton>
/> <Text ta='center' fz='lg' fw={500} mt='sm'>
)} {user.first_name} {user.last_name}
</FileButton> </Text>
<Text ta='center' fz='lg' fw={500} mt='sm'> <Text ta='center' fz='sm' c='dimmed' style={{ textTransform: 'uppercase' }}>
{user.first_name} {user.last_name} {user.role}
</Text> </Text>
<Text ta='center' fz='sm' c='dimmed' style={{ textTransform: 'uppercase' }}> <Grid mt='xl'>
{user.role} <Grid.Col span={6}>
</Text> <Link href='/profile'>
<Grid mt='xl'> <Button fullWidth radius='md' size='xs' variant='default'>
<Grid.Col span={6}> Profile
<Link href='/profile'> </Button>
</Link>
</Grid.Col>
<Grid.Col span={6}>
<Button
fullWidth
radius='md'
size='xs'
variant='default'
onClick={logout}
>
Logout
</Button>
</Grid.Col>
{user.role == 'admin' && (
<Grid.Col span={12}>
<Link href='/admin'>
<Button fullWidth radius='md' size='xs' variant='default'> <Button fullWidth radius='md' size='xs' variant='default'>
Profile Administration
</Button> </Button>
</Link> </Link>
</Grid.Col> </Grid.Col>
<Grid.Col span={6}> )}
<Button </Grid>
fullWidth </Card>
radius='md' </Menu.Dropdown>
size='xs' </Menu>
variant='default' ) : (
onClick={async () => { <Group className='user'>
await logout(); <Button onClick={() => toggle('login')}>Login</Button>
Cookies.remove('logged_in'); <Button variant='outline' onClick={() => toggle('register')}>
setUser(undefined); Sign up
setFavorites([]); </Button>
setProfilePicture(null); </Group>
if (refreshId) { )}
clearInterval(refreshId); </>
}
}}
>
Logout
</Button>
</Grid.Col>
{user.role == 'admin' && (
<Grid.Col span={12}>
<Link href='/admin'>
<Button fullWidth radius='md' size='xs' variant='default'>
Administration
</Button>
</Link>
</Grid.Col>
)}
</Grid>
</Card>
</Menu.Dropdown>
</Menu>
) : (
<Group className='user'>
<Button onClick={() => toggle('login')}>Login</Button>
<Button variant='outline' onClick={() => toggle('register')}>
Sign up
</Button>
</Group>
)}
</>
)}
</div> </div>
) )
} }

View File

@@ -0,0 +1,149 @@
'use client';
import { useEffect, useState } from "react";
import Header from "./Header";
import { useRecoilState } from "recoil";
import { refreshIdState, userState } from "@/state/auth";
import { login, logout, refresh, refreshLoggedIn, register } from "@/api/auth";
import { getFavorites, getPicture } from "@/api/users";
import Cookies from "js-cookie";
import { favoritesState, profilePictureState } from "@/state/user";
import { notifications } from "@mantine/notifications";
export default function Loader({ children }: { children: any }) {
const [loading, setLoading] = useState(true);
const [user, setUser] = useRecoilState(userState);
const [refreshId, setRefreshId] = useRecoilState(refreshIdState);
const [_, setFavorites] = useRecoilState(favoritesState);
const [profilePicture, setProfilePicture] = useRecoilState(profilePictureState);
useEffect(() => {
setLoading(true);
if (!user || !Cookies.get("logged_in")) {
refreshUser();
}
setLoading(false);
}, [user]);
function refreshUser() {
refresh().then((response) => {
if (response) {
setRefreshId(refreshLoggedIn());
setUser(response.user);
getFavorites().then((response) => {
if (response) {
setFavorites(response);
}
});
if (response.user.profile_picture) {
getPicture().then((response) => {
if (response) {
setProfilePicture(response as File);
}
});
}
}
});
}
async function loginUser({ email, password }: { email: string, password: string}): Promise<boolean> {
const loginResponse = await login(email, password);
if (loginResponse) {
setUser(loginResponse.user);
setRefreshId(refreshLoggedIn());
notifications.show({
title: `Welcome back ${loginResponse.user.first_name}!`,
message: `You have been logged in.`,
color: 'green',
autoClose: 2000,
loading: false
});
return true;
} else {
notifications.show({
title: `Unable to Login`,
message: `Please try again.`,
color: 'red',
autoClose: 2000,
loading: false
});
}
return false
}
async function logoutUser(): Promise<void> {
await logout();
Cookies.remove("logged_in");
setUser(undefined);
setFavorites([]);
setProfilePicture(undefined);
if (refreshId) {
clearInterval(refreshId);
setRefreshId(undefined);
}
}
async function registerUser({ firstName, lastName, email, password }: { firstName: string, lastName: string, email: string, password: string }): Promise<boolean> {
const id = notifications.show({
loading: true,
title: `Creating account`,
message: `Please wait...`,
autoClose: false,
withCloseButton: false
});
const registerResponse = await register({
first_name: firstName,
last_name: lastName,
email: email,
password: password
});
if (registerResponse) {
const loginResponse = await login(email, password);
if (loginResponse) {
setUser(loginResponse.user);
setRefreshId(refreshLoggedIn());
notifications.update({
id,
title: `Account created`,
message: `Welcome ${loginResponse.user.first_name}!`,
color: 'green',
autoClose: 2000,
loading: false
});
return true;
} else {
notifications.update({
id,
title: `Unable to Login`,
message: `Please try again.`,
color: 'red',
autoClose: 2000,
loading: false
});
}
} else {
notifications.update({
id,
title: `Unable to Register`,
message: `Please try again.`,
color: 'error',
autoClose: 2000,
loading: false
});
}
return false;
}
return (
<>
{loading ? (
<></>
) : (
<>
<Header user={user} profilePicture={profilePicture} setProfilePicture={setProfilePicture} login={loginUser} logout={logoutUser} register={registerUser} />
{children}
</>
)}
</>
)
}

View File

@@ -3,12 +3,10 @@
import { getAirports } from '@/api/airport'; import { getAirports } from '@/api/airport';
import { Airport, AirportOrderField } from '@/api/airport.types'; import { Airport, AirportOrderField } from '@/api/airport.types';
import { getMetars } from '@/api/metar'; import { getMetars } from '@/api/metar';
import { DivIcon, LatLngBounds } from 'leaflet'; import { LatLngBounds, icon } from 'leaflet';
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import ReactDOMServer from 'react-dom/server';
import { Marker, TileLayer, Tooltip, useMap, useMapEvents } from 'react-leaflet'; import { Marker, TileLayer, Tooltip, useMap, useMapEvents } from 'react-leaflet';
import MetarModal from './MetarModal'; import MetarModal from './MetarModal';
import { Avatar, MantineProvider } from '@mantine/core';
import { useRecoilState, useRecoilValue } from 'recoil'; import { useRecoilState, useRecoilValue } from 'recoil';
import { coordinatesState, zoomState } from '@/state/map'; import { coordinatesState, zoomState } from '@/state/map';
@@ -72,31 +70,20 @@ export default function MapTiles() {
} }
function metarIcon(airport: Airport) { function metarIcon(airport: Airport) {
function innerIcon({ tag, color, size = 'xs' }: { tag: string; color: string; size?: string }) { let iconUrl = '/icons/unkn.svg';
return new DivIcon({
html: ReactDOMServer.renderToString(
<MantineProvider>
<Avatar variant='filled' color={color} radius={'xl'} size={size}>
{tag}
</Avatar>
</MantineProvider>
),
className: 'metar-marker-icon'
});
}
if (airport.latest_metar?.flight_category == 'VFR') { if (airport.latest_metar?.flight_category == 'VFR') {
return innerIcon({ tag: 'V', color: 'green' }); iconUrl = '/icons/vfr.svg';
} else if (airport.latest_metar?.flight_category == 'MVFR') { } else if (airport.latest_metar?.flight_category == 'MVFR') {
return innerIcon({ tag: 'M', color: 'blue' }); iconUrl = '/icons/mvfr.svg';
} else if (airport.latest_metar?.flight_category == 'IFR') { } else if (airport.latest_metar?.flight_category == 'IFR') {
return innerIcon({ tag: 'I', color: 'red' }); iconUrl = '/icons/ifr.svg';
} else if (airport.latest_metar?.flight_category == 'LIFR') { } else if (airport.latest_metar?.flight_category == 'LIFR') {
return innerIcon({ tag: 'L', color: 'purple' }); iconUrl = '/icons/lifr.svg';
} else if (airport.latest_metar?.flight_category == 'UNKN') {
return innerIcon({ tag: 'U', color: 'black', size: 'xs' });
} else {
return innerIcon({tag: ' ', color: 'grey', size: 'xs' });
} }
return icon({
iconUrl: iconUrl,
iconSize: [20, 20]
})
} }
useEffect(() => { useEffect(() => {

View File

@@ -6,6 +6,11 @@ export const userState = atom({
default: undefined as User | undefined default: undefined as User | undefined
}); });
export const refreshIdState = atom({
key: 'refreshIdState',
default: undefined as NodeJS.Timeout | undefined
});
export const isAuthenticatedState = atom({ export const isAuthenticatedState = atom({
key: 'isAuthenticatedState', key: 'isAuthenticatedState',
default: false default: false

View File

@@ -4,3 +4,8 @@ export const favoritesState = atom({
key: 'favoritesState', key: 'favoritesState',
default: [] as string[] default: [] as string[]
}); });
export const profilePictureState = atom({
key: 'profilePictureState',
default: undefined as File | undefined
});

View File

@@ -30,7 +30,6 @@
"@api/*": ["src/api"], "@api/*": ["src/api"],
"@app/*": ["./src/app/*"], "@app/*": ["./src/app/*"],
"@components/*": ["src/components/*"], "@components/*": ["src/components/*"],
"@lib/*": ["src/components/*"]
} }
}, },
"include": [ "include": [