Skip to content

Commit

Permalink
Update formatting a subdivide user & userentry
Browse files Browse the repository at this point in the history
  • Loading branch information
lucemans committed Dec 1, 2024
1 parent 75ff4b6 commit 6331527
Show file tree
Hide file tree
Showing 31 changed files with 172 additions and 131 deletions.
2 changes: 2 additions & 0 deletions engine/rustfmt.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
reorder_imports = true
# group_imports = "StdExternalCrate"
2 changes: 1 addition & 1 deletion engine/src/auth/middleware.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use reqwest::StatusCode;

use crate::{models::sessions::Session, state::AppState};

use super::{hash::hash_session};
use super::hash::hash_session;

pub struct ActiveUser {
pub session: Session,
Expand Down
11 changes: 7 additions & 4 deletions engine/src/ingress/product/tweakers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,22 @@ pub enum TweakerError {
// price data
// https://tweakers.net/ajax/price_chart/1855004/nl/?output=json


// Fetch https://tweakers.net/pricewatch/1855004/anker-737-power-bank-powercore-24k/specificaties/
// and parse the application/ld+json
pub async fn get_by_tweaker_id(tweaker_id: String) -> Result<TweakerProduct, TweakerError> {

let response = reqwest::get(format!("https://tweakers.net/pricewatch/{}/specificaties/", tweaker_id)).await.unwrap();
let response = reqwest::get(format!(
"https://tweakers.net/pricewatch/{}/specificaties/",
tweaker_id
))
.await
.unwrap();
let body = response.text().await.unwrap();

// println!("{}", body);
// // regex match for <script type="application/ld+json"> ... </script>
// let re = regex::Regex::new(r#"<script type="application/ld\+json">\s*?(.*?)\s*?</script>"#).unwrap();
// let captures = re.captures(&body).unwrap();

// for capture in captures.iter() {
// println!("{}", capture.unwrap().as_str());
// }
Expand Down
6 changes: 3 additions & 3 deletions engine/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ use terminal_banner::Banner;
use tracing::info;

mod auth;
mod state;
mod database;
mod ingress;
mod models;
mod routes;
mod ingress;
mod database;
mod state;

#[async_std::main]
async fn main() {
Expand Down
2 changes: 1 addition & 1 deletion engine/src/models/field/definition.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::database::Database;
use crate::models::field::kind::FieldKind;
use serde::{Deserialize, Serialize};
use poem_openapi::Object;
use serde::{Deserialize, Serialize};
use sqlx::{query_as, FromRow};

#[derive(FromRow, Object, Debug, Clone, Serialize, Deserialize)]
Expand Down
2 changes: 1 addition & 1 deletion engine/src/models/field/kind.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use poem_openapi::Enum;
use serde::{Deserialize, Serialize};
use sqlx::Type;
use poem_openapi::Enum;

#[derive(Type, Enum, Debug, Clone, Serialize, Deserialize)]
#[sqlx(type_name = "text")]
Expand Down
2 changes: 1 addition & 1 deletion engine/src/models/field/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
pub mod kind;
pub mod definition;
pub mod kind;
1 change: 0 additions & 1 deletion engine/src/models/item/field.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

use crate::database::Database;
use serde::{Deserialize, Serialize};
use sqlx::query_as;
Expand Down
10 changes: 7 additions & 3 deletions engine/src/models/item/mod.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use sqlx::{query, query_as};
use tracing::info;
use chrono::{DateTime, Utc};

use crate::database::Database;

Expand Down Expand Up @@ -64,7 +64,10 @@ impl Item {
.await
}

pub async fn get_by_id(item_id: String, database: &Database) -> Result<Option<Item>, sqlx::Error> {
pub async fn get_by_id(
item_id: String,
database: &Database,
) -> Result<Option<Item>, sqlx::Error> {
query_as!(Item, "SELECT * FROM items WHERE item_id = $1", item_id)
.fetch_optional(&database.pool)
.await
Expand All @@ -83,7 +86,8 @@ impl Item {
.bind(id_str.clone())
.fetch_optional(&database.pool)
.await
.unwrap().is_none()
.unwrap()
.is_none()
{
return Ok(id_str);
}
Expand Down
2 changes: 1 addition & 1 deletion engine/src/models/location.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use serde::{Deserialize, Serialize};
use chrono::{DateTime, Utc};
use poem_openapi::Object;
use serde::{Deserialize, Serialize};
use sqlx::{query_as, FromRow};

use crate::database::Database;
Expand Down
21 changes: 13 additions & 8 deletions engine/src/models/log/mod.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use sqlx::{prelude::FromRow, query_as};
use serde::{Deserialize, Serialize};
use chrono::{DateTime, Utc};
use poem_openapi::Object;
use serde::{Deserialize, Serialize};
use sqlx::{prelude::FromRow, query_as};

use crate::database::Database;

Expand All @@ -22,7 +22,14 @@ pub struct LogEntry {
impl LogEntry {
/// Create a new log entry
/// Let postgres generate the id and created_at
pub async fn new(db: &Database, resource_type: String, resource_id: i32, user_id: i32, action: String, data: String) -> Result<Self, sqlx::Error> {
pub async fn new(
db: &Database,
resource_type: String,
resource_id: i32,
user_id: i32,
action: String,
data: String,
) -> Result<Self, sqlx::Error> {
let log_entry = query_as!(
LogEntry,
"INSERT INTO logs (resource_type, resource_id, user_id, action, data) VALUES ($1, $2, $3, $4, $5) RETURNING *",
Expand All @@ -34,11 +41,9 @@ impl LogEntry {

/// Find by log_id
pub async fn find_by_log_id(db: &Database, log_id: i32) -> Result<Self, sqlx::Error> {
let log_entry = query_as!(
LogEntry,
"SELECT * FROM logs WHERE log_id = $1",
log_id
).fetch_one(&db.pool).await?;
let log_entry = query_as!(LogEntry, "SELECT * FROM logs WHERE log_id = $1", log_id)
.fetch_one(&db.pool)
.await?;

Ok(log_entry)
}
Expand Down
11 changes: 4 additions & 7 deletions engine/src/models/media.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use crate::database::Database;
use chrono::{DateTime, Utc};
use poem_openapi::Object;
use serde::{Deserialize, Serialize};
use sqlx::{query_as, FromRow};
use poem_openapi::Object;
use chrono::{DateTime, Utc};
use crate::database::Database;

#[derive(FromRow, Object, Debug, Clone, Serialize, Deserialize)]
pub struct Media {
Expand Down Expand Up @@ -32,10 +32,7 @@ impl Media {
.await
}

pub async fn get_by_id(
media_id: i32,
database: &Database,
) -> Result<Media, sqlx::Error> {
pub async fn get_by_id(media_id: i32, database: &Database) -> Result<Media, sqlx::Error> {
query_as!(Media, "SELECT * FROM media WHERE media_id = $1", media_id)
.fetch_one(&database.pool)
.await
Expand Down
4 changes: 2 additions & 2 deletions engine/src/models/mod.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
pub mod field;
pub mod item;
pub mod location;
pub mod log;
pub mod media;
pub mod products;
pub mod sessions;
pub mod tags;
pub mod users;
pub mod log;
pub mod user;
21 changes: 14 additions & 7 deletions engine/src/models/products.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use crate::database::Database;
use chrono::{DateTime, Utc};
use poem_openapi::Object;
use serde::{Deserialize, Serialize};
use sqlx::{query_as, FromRow};
use poem_openapi::Object;
use chrono::{DateTime, Utc};
use crate::database::Database;

#[derive(FromRow, Object, Debug, Clone, Serialize, Deserialize)]
pub struct Product {
Expand All @@ -23,9 +23,16 @@ impl Product {
.await
}

pub async fn get_by_id(product_id: i32, database: &Database) -> Result<Option<Product>, sqlx::Error> {
query_as!(Product, "SELECT * FROM products WHERE product_id = $1", product_id)
.fetch_optional(&database.pool)
.await
pub async fn get_by_id(
product_id: i32,
database: &Database,
) -> Result<Option<Product>, sqlx::Error> {
query_as!(
Product,
"SELECT * FROM products WHERE product_id = $1",
product_id
)
.fetch_optional(&database.pool)
.await
}
}
2 changes: 1 addition & 1 deletion engine/src/models/sessions.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use chrono::{DateTime, Utc};
use poem_openapi::Object;
use serde::{Deserialize, Serialize};
use sqlx::{query_as, types::ipnetwork::IpNetwork};
use chrono::{DateTime, Utc};

use crate::database::Database;

Expand Down
6 changes: 3 additions & 3 deletions engine/src/models/tags.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use serde::{Deserialize, Serialize};
use sqlx::{query_as, FromRow};
use crate::database::Database;
use chrono::{DateTime, Utc};
use poem_openapi::Object;
use crate::database::Database;
use serde::{Deserialize, Serialize};
use sqlx::{query_as, FromRow};

#[derive(FromRow, Object, Debug, Clone, Serialize, Deserialize)]
pub struct Tag {
Expand Down
2 changes: 2 additions & 0 deletions engine/src/models/user/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
pub mod user;
pub mod userentry;
31 changes: 31 additions & 0 deletions engine/src/models/user/user.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
use poem_openapi::Object;
use serde::{Deserialize, Serialize};
use url::Url;

use super::userentry::UserEntry;

/// A user object that is returned to the client
/// This is a subset of the `UserEntry` struct
/// Use `UserEntry` to query the database for a user
#[derive(Debug, Clone, Serialize, Deserialize, Object)]
pub struct User {
pub id: i32,
pub oauth_sub: String,
pub name: String,
pub picture: Option<Url>,
}

impl From<UserEntry> for User {
fn from(user: UserEntry) -> Self {
Self {
id: user.user_id,
oauth_sub: user.oauth_sub,
name: user
.nickname
.or(user.oauth_data.nickname.clone())
.or(user.oauth_data.name.clone())
.unwrap_or("Unknown".to_string()),
picture: user.oauth_data.picture.clone(),
}
}
}
32 changes: 2 additions & 30 deletions engine/src/models/users.rs → engine/src/models/user/userentry.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
use crate::database::Database;
use chrono::{DateTime, Utc};
use openid::Userinfo;
use serde::{Deserialize, Serialize};
use sqlx::{query, query_as, types::Json, FromRow};
use url::Url;
use chrono::{DateTime, Utc};
use poem_openapi::Object;
use crate::database::Database;

/// A user object that is stored in the database
#[derive(FromRow, Debug, Clone, Serialize, Deserialize)]
Expand Down Expand Up @@ -68,29 +66,3 @@ impl UserEntry {
.await
}
}

/// A user object that is returned to the client
/// This is a subset of the `UserEntry` struct
/// Use `UserEntry` to query the database for a user
#[derive(Debug, Clone, Serialize, Deserialize, Object)]
pub struct User {
pub id: i32,
pub oauth_sub: String,
pub name: String,
pub picture: Option<Url>,
}

impl From<UserEntry> for User {
fn from(user: UserEntry) -> Self {
Self {
id: user.user_id,
oauth_sub: user.oauth_sub,
name: user
.nickname
.or(user.oauth_data.nickname.clone())
.or(user.oauth_data.name.clone())
.unwrap_or("Unknown".to_string()),
picture: user.oauth_data.picture.clone(),
}
}
}
6 changes: 3 additions & 3 deletions engine/src/routes/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,16 @@ pub enum HttpError {
NotFound,
}

impl ResponseError for HttpError{
impl ResponseError for HttpError {
fn status(&self) -> StatusCode {
match self {
HttpError::NotFound => StatusCode::NOT_FOUND,
}
}

fn as_response(&self) -> Response
where
Self: std::error::Error + Send + Sync + 'static,
where
Self: std::error::Error + Send + Sync + 'static,
{
self.status().into_response()
}
Expand Down
30 changes: 18 additions & 12 deletions engine/src/routes/instance.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::sync::Arc;

use poem::web::{Data};
use poem::web::Data;
use poem_openapi::{payload::Json, Enum, Object, OpenApi};
use serde::{Deserialize, Serialize};

Expand All @@ -25,24 +25,30 @@ pub struct InstanceSettings {

impl Default for InstanceSettings {
fn default() -> Self {
Self { id_casing_preference: IdCasingPreference::Upper }
Self {
id_casing_preference: IdCasingPreference::Upper,
}
}
}

#[OpenApi]
impl ApiInstance {
#[oai(path = "/instance/settings", method = "get")]
pub async fn settings(&self, state: Data<&Arc<AppState>>, token: AuthToken) -> Json<InstanceSettings> {
pub async fn settings(
&self,
state: Data<&Arc<AppState>>,
token: AuthToken,
) -> Json<InstanceSettings> {
// match token {
// AuthToken::Active(active_user) => {
// TODO: check if user has permission to access this resource
Json(InstanceSettings::default())
// }
// _ => {
// Error::from_string("Not Authenticated", StatusCode::UNAUTHORIZED).into_response(),
// panic!()
// }
// AuthToken::Active(active_user) => {
// TODO: check if user has permission to access this resource

Json(InstanceSettings::default())
// }
// _ => {
// Error::from_string("Not Authenticated", StatusCode::UNAUTHORIZED).into_response(),
// panic!()
// }
// }
}
}
Loading

0 comments on commit 6331527

Please sign in to comment.