Skip to content

Commit

Permalink
Fixed log level regression & formatted everything
Browse files Browse the repository at this point in the history
  • Loading branch information
CEbbinghaus committed Feb 13, 2024
1 parent 21df376 commit d23c985
Show file tree
Hide file tree
Showing 10 changed files with 77 additions and 62 deletions.
9 changes: 3 additions & 6 deletions backend/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,15 @@ use crate::{
sdcard::{get_card_cid, is_card_inserted},
};
use actix_web::{
delete, get,
http::StatusCode,
post,
web,
Either, HttpResponse, HttpResponseBuilder, Responder, Result,
delete, get, http::StatusCode, post, web, Either, HttpResponse, HttpResponseBuilder, Responder,
Result,
};
use futures::StreamExt;
use serde::Deserialize;
use tracing::{instrument, trace};
use std::{ops::Deref, sync::Arc};
use tokio::sync::broadcast::Sender;
use tokio_stream::wrappers::BroadcastStream;
use tracing::{instrument, trace};

pub(crate) fn config(cfg: &mut web::ServiceConfig) {
cfg //
Expand Down
4 changes: 2 additions & 2 deletions backend/src/ds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ use crate::{
err::Error,
sdcard::get_steam_acf_files,
};
use tracing::{error, instrument};
use semver::Version;
use serde::{Deserialize, Serialize};
use slotmap::{DefaultKey, SlotMap};
Expand All @@ -16,6 +15,7 @@ use std::{
path::PathBuf,
sync::RwLock,
};
use tracing::{error, instrument};

#[derive(Serialize, Deserialize, Debug, Clone)]
pub(crate) enum StoreElement {
Expand Down Expand Up @@ -66,7 +66,7 @@ fn default_version() -> Version {

#[derive(Serialize, Deserialize, Debug)]
pub struct StoreData {
#[serde(default="default_version")]
#[serde(default = "default_version")]
version: Version,
nodes: SlotMap<DefaultKey, Node>,
node_ids: HashMap<String, DefaultKey>,
Expand Down
10 changes: 5 additions & 5 deletions backend/src/dto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,17 @@ use serde::{Deserialize, Serialize};
pub enum CardEvent {
Inserted,
Removed,
Updated
Updated,
}

impl EventTrait for CardEvent {
fn get_event(&self) -> Option<&'static str> {
Some(match self {
fn get_event(&self) -> Option<&'static str> {
Some(match self {
CardEvent::Inserted => "insert",
CardEvent::Removed => "remove",
CardEvent::Updated => "update",
})
}
}
// fn get_data(&self) -> Option<&'static str> {
// match self {
// CardEvent::Inserted => None,
Expand All @@ -33,7 +33,7 @@ fn default_true() -> bool {
pub struct MicroSDCard {
pub uid: String,
pub libid: String,

#[serde(default)]
pub mount: Option<String>,

Expand Down
1 change: 0 additions & 1 deletion backend/src/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ pub fn get_file_path_and_create_directory(
file_name: &PathBuf,
base_dir: &PathBuf,
) -> Option<PathBuf> {

if let Err(_) = std::fs::create_dir_all(base_dir) {
return None;
}
Expand Down
12 changes: 5 additions & 7 deletions backend/src/err.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
#![allow(dead_code)]


use std::fmt;

use actix_web::ResponseError;
use std::fmt;

#[derive(Debug)]
struct StdErr;

impl std::error::Error for StdErr{}
impl std::error::Error for StdErr {}

impl fmt::Display for StdErr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Expand Down Expand Up @@ -40,9 +38,9 @@ impl fmt::Display for Error {
}

impl Into<Box<dyn std::error::Error>> for Error {
fn into(self) -> Box<dyn std::error::Error> {
Box::new(StdErr)
}
fn into(self) -> Box<dyn std::error::Error> {
Box::new(StdErr)
}
}

impl<T: std::error::Error + Send + Sync + 'static> From<T> for Error {
Expand Down
34 changes: 19 additions & 15 deletions backend/src/event.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use actix_web::web::Bytes;

pub(crate) struct Event<T : EventTrait> {
val: T
pub(crate) struct Event<T: EventTrait> {
val: T,
}

pub(crate) trait EventTrait {
Expand All @@ -22,18 +22,18 @@ impl<T: EventTrait> Event<T> {
}
}

impl<T : EventTrait> ToString for Event<T> {
fn to_string(&self) -> String {
let mut output = "".to_string();
impl<T: EventTrait> ToString for Event<T> {
fn to_string(&self) -> String {
let mut output = "".to_string();

if let Some(value) = self.val.get_id() {
output += &format!("id: {}\n", value);
}
if let Some(value) = self.val.get_event() {
output += &format!("event: {}\n", value);
output += &format!("event: {}\n", value);
}
if let Some(value) = self.val.get_data() {
output += &format!("data: {}\n", value);
output += &format!("data: {}\n", value);
}

if output != "" {
Expand All @@ -45,15 +45,15 @@ impl<T : EventTrait> ToString for Event<T> {
}

impl<T: EventTrait> Into<Bytes> for Event<T> {
fn into(self) -> Bytes {
Bytes::from(self.to_string())
}
fn into(self) -> Bytes {
Bytes::from(self.to_string())
}
}

impl<T: EventTrait> From<T> for Event<T> {
fn from(value: T) -> Self {
Event { val: value }
}
fn from(value: T) -> Self {
Event { val: value }
}
}

pub(crate) struct EventBuilder {
Expand All @@ -65,7 +65,11 @@ pub(crate) struct EventBuilder {
#[allow(dead_code)]
impl EventBuilder {
pub fn new() -> Self {
EventBuilder { id: None, event: None, data: None }
EventBuilder {
id: None,
event: None,
data: None,
}
}
pub fn with_id(mut self, id: &'static str) -> Self {
self.id = Some(id);
Expand All @@ -91,4 +95,4 @@ impl EventTrait for EventBuilder {
fn get_id(&self) -> Option<&'static str> {
self.id
}
}
}
22 changes: 14 additions & 8 deletions backend/src/log.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
use crate::cfg::CONFIG;
use crate::{get_file_path_and_create_directory, LOG_DIR};
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
use tracing_subscriber::Layer;

pub fn create_subscriber() {
let log_file_path = get_file_path_and_create_directory(&CONFIG.log_file, &LOG_DIR).expect("Log file to be created");
let log_file_path = get_file_path_and_create_directory(&CONFIG.log_file, &LOG_DIR)
.expect("Log file to be created");

let file = std::fs::OpenOptions::new()
.create(true)
Expand All @@ -14,13 +16,17 @@ pub fn create_subscriber() {

let file_writer = tracing_subscriber::fmt::layer()
.json()
.with_writer(file);
.with_writer(file)
.with_filter(tracing_subscriber::filter::LevelFilter::from_level(
CONFIG.log_level,
));

let subscriber = tracing_subscriber::registry().with(file_writer);

let subscriber = tracing_subscriber::registry()
.with(file_writer);

if cfg!(debug_assertions) {
subscriber.with(tracing_subscriber::fmt::layer().pretty()).init();
subscriber
.with(tracing_subscriber::fmt::layer().pretty())
.init();
} else {
subscriber.init();
}
Expand Down
3 changes: 1 addition & 2 deletions backend/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,7 @@ async fn main() {

info!(
version = PACKAGE_VERSION,
"{}@{} by {}",
PACKAGE_NAME, PACKAGE_VERSION, PACKAGE_AUTHORS
"{}@{} by {}", PACKAGE_NAME, PACKAGE_VERSION, PACKAGE_AUTHORS
);

let store_path = PathBuf::from(
Expand Down
7 changes: 1 addition & 6 deletions backend/src/steam.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,7 @@ pub struct LibraryFolder {
pub label: String,
}

#[serde_alias(
CamelCase,
PascalCase,
LowerCase,
SnakeCase
)]
#[serde_alias(CamelCase, PascalCase, LowerCase, SnakeCase)]
#[derive(Deserialize)]
pub struct AppState {
pub appid: String,
Expand Down
37 changes: 27 additions & 10 deletions backend/src/watch.rs
Original file line number Diff line number Diff line change
@@ -1,24 +1,32 @@
use crate::{ds::Store, dto::*, err::Error, sdcard::*, steam::*};
use tracing::{debug, error, info, span, trace, warn};
use std::borrow::Borrow;
use std::path::{Path, PathBuf};
use std::{fs, sync::Arc, time::Duration};
use tokio::sync::broadcast::Sender;
use tokio::time::interval;
use tracing::{debug, error, info, span, trace, warn};

fn read_msd_directory(datastore: &Store, mount: &Option<String>) -> Result<(), Error> {
let cid = get_card_cid().ok_or(Error::from_str("Unable to retrieve CID from MicroSD card"))?;

let library: LibraryFolder = keyvalues_serde::from_str(&read_libraryfolder(mount)?)?;

debug!(?library, "Read & deserialized library from {}", LIBRARY_FOLDER_FILE);
debug!(
?library,
"Read & deserialized library from {}", LIBRARY_FOLDER_FILE
);

let games: Vec<AppState> = get_steam_acf_files(mount)?
.filter_map(|f| fs::read_to_string(f.path()).ok())
.filter_map(|s| keyvalues_serde::from_str(s.as_str()).ok())
.collect();

debug!(game_count = games.len(), ?games, "Retrieved {} Games from acf files", games.len());
debug!(
game_count = games.len(),
?games,
"Retrieved {} Games from acf files",
games.len()
);

if !datastore.contains_element(&cid) {
debug!(cid, "No MicroSD card found, creating new card");
Expand All @@ -38,7 +46,11 @@ fn read_msd_directory(datastore: &Store, mount: &Option<String>) -> Result<(), E

// Remove any games that are linked to the card in the database but on the card
let current_games = datastore.get_games_on_card(&cid)?;
debug!(?current_games, "Retrieved {} Games from database", current_games.len());
debug!(
?current_games,
"Retrieved {} Games from database",
current_games.len()
);
for deleted_game in current_games
.iter()
.filter(|v| !games.iter().any(|g| g.appid == v.uid))
Expand Down Expand Up @@ -68,7 +80,6 @@ fn read_msd_directory(datastore: &Store, mount: &Option<String>) -> Result<(), E
Ok(())
}


pub async fn start_watch(datastore: Arc<Store>, sender: Sender<CardEvent>) -> Result<(), Error> {
let mut interval = interval(Duration::from_secs(1));

Expand Down Expand Up @@ -110,7 +121,7 @@ pub async fn start_watch(datastore: Arc<Store>, sender: Sender<CardEvent>) -> Re
Some(v) => {
trace!(card_id = v, "{}", v);
v
},
}
None => {
error!("Unable to read Card ID");
continue;
Expand All @@ -129,15 +140,21 @@ pub async fn start_watch(datastore: Arc<Store>, sender: Sender<CardEvent>) -> Re
// Try and retrieve the mount from the database
if let Some(card) = datastore.get_card(&cid).ok() {
if card.mount != None {
debug!(mount = card.mount, "MicroSD card had preexisting mount saved. Reusing that.");
debug!(
mount = card.mount,
"MicroSD card had preexisting mount saved. Reusing that."
);
}
mount = card.mount
}
}

// Whatever we loaded did not work.
if mount != None && !has_libraryfolder(&mount) {
warn!(mount = mount, "loaded mount does not resolve library. Resetting mount");
warn!(
mount = mount,
"loaded mount does not resolve library. Resetting mount"
);
mount = None;
}

Expand Down Expand Up @@ -170,8 +187,8 @@ pub async fn start_watch(datastore: Arc<Store>, sender: Sender<CardEvent>) -> Re
let hash = match datastore.is_hash_changed(&cid, &mount) {
None => {
debug!("No hash found. Skipping iteration");
continue
},
continue;
}
Some(v) => v,
};

Expand Down

0 comments on commit d23c985

Please sign in to comment.