diff --git a/src/database/database.rs b/src/database/database.rs index 505d02fb..f3b1f402 100644 --- a/src/database/database.rs +++ b/src/database/database.rs @@ -1,11 +1,12 @@ -use diesel::prelude::*; use diesel::pg::PgConnection; +use diesel::prelude::*; use dotenv::dotenv; use std::env; -pub fn connect() -> PgConnection{ +pub fn connect() -> PgConnection { dotenv().ok(); let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set!"); - PgConnection::establish(&database_url).expect(&format!("Error connecting to {}", database_url)) -} \ No newline at end of file + PgConnection::establish(&database_url) + .unwrap_or_else(|_| panic!("Error connecting to {}", database_url)) +} diff --git a/src/database/mod.rs b/src/database/mod.rs index f9674f87..921a03eb 100644 --- a/src/database/mod.rs +++ b/src/database/mod.rs @@ -3,4 +3,4 @@ mod models; pub use database::connect; pub use models::Mod; -pub use models::Version; \ No newline at end of file +pub use models::Version; diff --git a/src/database/models.rs b/src/database/models.rs index 6cc48c14..93305650 100644 --- a/src/database/models.rs +++ b/src/database/models.rs @@ -10,7 +10,7 @@ pub struct Mod { pub downloads: i32, pub categories: Vec, pub body_path: String, - pub icon_path: String + pub icon_path: String, } #[derive(Queryable)] @@ -20,10 +20,9 @@ pub struct Version { pub title: String, pub changelog_path: String, pub files_path: Vec, - pub date_published: NaiveDate, + pub date_published: NaiveDate, pub author: String, pub downloads: i32, pub dependencies: Vec, - pub game_versions: Vec + pub game_versions: Vec, } - diff --git a/src/helpers/contains.rs b/src/helpers/contains.rs index cca5ce29..35066156 100644 --- a/src/helpers/contains.rs +++ b/src/helpers/contains.rs @@ -4,15 +4,32 @@ use handlebars::*; pub struct ContainsHelper; impl HelperDef for ContainsHelper { - fn call<'reg: 'rc, 'rc>(&self, h: &Helper<'reg, 'rc>, r: &'reg Handlebars<'_>, ctx: &'rc Context, rc: &mut RenderContext<'reg, 'rc>, out: &mut dyn Output) -> HelperResult { - let array = h.param(0).map(|v| serde_json::from_value::>(v.value().clone()).unwrap()).ok_or(RenderError::new("Parameter not found!"))?; - let value = h.param(1).map(|v| v.value().as_str().unwrap()).ok_or(RenderError::new("Parameter not found!"))?; + fn call<'reg: 'rc, 'rc>( + &self, + h: &Helper<'reg, 'rc>, + r: &'reg Handlebars<'_>, + ctx: &'rc Context, + rc: &mut RenderContext<'reg, 'rc>, + out: &mut dyn Output, + ) -> HelperResult { + let array = h + .param(0) + .map(|v| serde_json::from_value::>(v.value().clone()).unwrap()) + .ok_or_else(|| RenderError::new("Parameter not found!"))?; + let value = h + .param(1) + .map(|v| v.value().as_str().unwrap()) + .ok_or_else(|| RenderError::new("Parameter not found!"))?; - let tmpl = if array.contains(&String::from(value)) { h.template() } else { h.inverse() }; + let tmpl = if array.contains(&String::from(value)) { + h.template() + } else { + h.inverse() + }; match tmpl { Some(ref t) => t.render(r, ctx, rc, out), None => Ok(()), } } -} \ No newline at end of file +} diff --git a/src/helpers/format_human.rs b/src/helpers/format_human.rs index 3f481aff..db15b410 100644 --- a/src/helpers/format_human.rs +++ b/src/helpers/format_human.rs @@ -5,7 +5,14 @@ use handlebars::*; pub struct HumanFormatHelper; impl HelperDef for HumanFormatHelper { - fn call<'reg: 'rc, 'rc>(&self, h: &Helper<'reg, 'rc>, r: &'reg Handlebars<'_>, ctx: &'rc Context, rc: &mut RenderContext<'reg, 'rc>, out: &mut dyn Output) -> HelperResult { + fn call<'reg: 'rc, 'rc>( + &self, + h: &Helper<'reg, 'rc>, + _r: &'reg Handlebars<'_>, + _ctx: &'rc Context, + _rc: &mut RenderContext<'reg, 'rc>, + out: &mut dyn Output, + ) -> HelperResult { let param = h.param(0).and_then(|v| v.value().as_f64()).unwrap_or(0.0); let mut formatted = human_format::Formatter::new().format(param); @@ -15,4 +22,4 @@ impl HelperDef for HumanFormatHelper { Ok(()) } -} \ No newline at end of file +} diff --git a/src/helpers/mod.rs b/src/helpers/mod.rs index 0c271160..bd00ba6b 100644 --- a/src/helpers/mod.rs +++ b/src/helpers/mod.rs @@ -2,4 +2,4 @@ mod contains; mod format_human; pub use contains::ContainsHelper; -pub use format_human::HumanFormatHelper; \ No newline at end of file +pub use format_human::HumanFormatHelper; diff --git a/src/main.rs b/src/main.rs index fd3972c2..d69a7039 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,14 +4,14 @@ extern crate serde_json; #[macro_use] extern crate diesel; +use actix_files as fs; use actix_web::{web, App, HttpServer}; use handlebars::*; -use actix_files as fs; -mod schema; -mod routes; -mod helpers; mod database; +mod helpers; +mod routes; +mod schema; #[actix_rt::main] async fn main() -> std::io::Result<()> { @@ -39,8 +39,7 @@ async fn main() -> std::io::Result<()> { .service(routes::search_get) .service(routes::mod_editor_get) }) - .bind("127.0.0.1:8000")? - .run() - .await + .bind("127.0.0.1:8000")? + .run() + .await } - diff --git a/src/routes/index.rs b/src/routes/index.rs index 0ca4ed93..9f981a36 100644 --- a/src/routes/index.rs +++ b/src/routes/index.rs @@ -1,4 +1,4 @@ -use actix_web::{web, HttpResponse, get, post}; +use actix_web::{get, web, HttpResponse}; use handlebars::*; #[get("/")] @@ -9,4 +9,4 @@ pub async fn index_get(hb: web::Data>) -> HttpResponse { let body = hb.render("index", &data).unwrap(); HttpResponse::Ok().body(body) -} \ No newline at end of file +} diff --git a/src/routes/mod.rs b/src/routes/mod.rs index 0149d5ed..f5a5fe89 100644 --- a/src/routes/mod.rs +++ b/src/routes/mod.rs @@ -1,11 +1,11 @@ -mod search; mod index; mod mod_editor; +mod search; pub use self::mod_editor::mod_editor_get; +pub use self::search::index_mods; pub use self::search::search_get; pub use self::search::search_post; -pub use self::search::index_mods; -pub use self::index::index_get; \ No newline at end of file +pub use self::index::index_get; diff --git a/src/routes/mod_editor.rs b/src/routes/mod_editor.rs index 84de4d83..f5903faf 100644 --- a/src/routes/mod_editor.rs +++ b/src/routes/mod_editor.rs @@ -1,4 +1,4 @@ -use actix_web::{web, HttpResponse, get, post}; +use actix_web::{get, web, HttpResponse}; use handlebars::*; #[get("modeditor")] @@ -9,4 +9,4 @@ pub async fn mod_editor_get(hb: web::Data>) -> HttpResponse { let body = hb.render("mod_editor", &data).unwrap(); HttpResponse::Ok().body(body) -} \ No newline at end of file +} diff --git a/src/routes/search.rs b/src/routes/search.rs index 50eafbec..cbac8d55 100644 --- a/src/routes/search.rs +++ b/src/routes/search.rs @@ -1,21 +1,20 @@ extern crate diesel; -use actix_web::{web, web::Data, HttpRequest, HttpResponse, get, post}; +use actix_web::{get, post, web, web::Data, HttpResponse}; use handlebars::*; -use meilisearch_sdk::{document::*, indexes::*, client::*, search::*}; -use serde::{Serialize, Deserialize}; +use meilisearch_sdk::{client::*, document::*, search::*}; +use serde::{Deserialize, Serialize}; use crate::database::*; use diesel::prelude::*; -use actix_web::client::Connector; + use meilisearch_sdk::settings::Settings; -use meilisearch_sdk::progress::SettingsUpdate; -use serde_json::from_str; #[derive(Serialize, Deserialize, Debug)] +#[serde(rename_all = "camelCase")] struct Attachment { url: String, - isDefault: bool, + is_default: bool, } #[derive(Serialize, Deserialize, Debug)] @@ -30,23 +29,25 @@ struct Author { } #[derive(Serialize, Deserialize, Debug)] +#[serde(rename_all = "camelCase")] struct CurseVersion { - gameVersion: String, + game_version: String, } #[derive(Serialize, Deserialize, Debug)] +#[serde(rename_all = "camelCase")] struct CurseForgeMod { id: i32, name: String, authors: Vec, attachments: Vec, - websiteUrl: String, + website_url: String, summary: String, - downloadCount: f32, + download_count: f32, categories: Vec, - gameVersionLatestFiles: Vec, - dateCreated: String, - dateModified: String, + game_version_latest_files: Vec, + date_created: String, + date_modified: String, } #[derive(Serialize, Deserialize, Debug)] @@ -84,11 +85,14 @@ pub struct SearchRequest { } #[post("search")] -pub async fn search_post(web::Query(info): web::Query, hb: Data>) -> HttpResponse { +pub async fn search_post( + web::Query(info): web::Query, + hb: Data>, +) -> HttpResponse { let results = search(web::Query(info)); let data = json!({ - "results": results, + "results": results, }); let body = hb.render("search-results", &data).unwrap(); @@ -97,11 +101,14 @@ pub async fn search_post(web::Query(info): web::Query, hb: Data, hb: Data>) -> HttpResponse { +pub async fn search_get( + web::Query(info): web::Query, + hb: Data>, +) -> HttpResponse { let results = search(web::Query(info)); let data = json!({ - "results": results, + "results": results, }); let body = hb.render("search", &data).unwrap(); @@ -110,15 +117,15 @@ pub async fn search_get(web::Query(info): web::Query, hb: Data) -> Vec { - let client = Client::new("http://localhost:7700", ""); + let client = Client::new("http://localhost:7700", ""); - let mut search_query = "".to_string(); + let search_query: String; let mut filters = "".to_string(); let mut offset = 0; match info.q { Some(q) => search_query = q, - None => search_query = "{}{}{}".to_string() + None => search_query = "{}{}{}".to_string(), } if let Some(f) = info.f { @@ -128,8 +135,7 @@ fn search(web::Query(info): web::Query) -> Vec { if let Some(v) = info.v { if filters.is_empty() { filters = v; - } - else { + } else { filters = format!("({}) AND {}", filters, v); } } @@ -141,24 +147,32 @@ fn search(web::Query(info): web::Query) -> Vec { let mut query = Query::new(&search_query).with_limit(10).with_offset(offset); if !filters.is_empty() { - query = Query::new(&search_query).with_limit(10).with_filters(&filters).with_offset(offset); + query = query.with_filters(&filters); } - client.get_index("mods").unwrap().search::(&query).unwrap().hits + client + .get_index("mods") + .unwrap() + .search::(&query) + .unwrap() + .hits } -pub async fn index_mods(conn : PgConnection) { +pub async fn index_mods(conn: PgConnection) { use crate::schema::mods::dsl::*; use crate::schema::versions::dsl::*; - let client = Client::new("http://localhost:7700", ""); + let client = Client::new("http://localhost:7700", ""); let mut mods_index = client.get_or_create("mods").unwrap(); let results = mods.load::(&conn).expect("Error loading mods!"); - let mut docs_to_add : Vec = vec![]; + let mut docs_to_add: Vec = vec![]; for result in results { - let mod_versions = versions.filter(mod_id.eq(result.id)).load::(&conn).expect("Error loading versions!"); + let mod_versions = versions + .filter(mod_id.eq(result.id)) + .load::(&conn) + .expect("Error loading versions!"); let mut mod_game_versions = vec![]; @@ -180,7 +194,7 @@ pub async fn index_mods(conn : PgConnection) { date_created: "".to_string(), date_modified: "".to_string(), latest_version: "".to_string(), - empty: String::from("{}{}{}") + empty: String::from("{}{}{}"), }); } @@ -189,20 +203,25 @@ pub async fn index_mods(conn : PgConnection) { .text() .await.unwrap(); - let curseforge_mods : Vec = serde_json::from_str(&body).unwrap(); + let curseforge_mods: Vec = serde_json::from_str(&body).unwrap(); for curseforge_mod in curseforge_mods { let mut mod_game_versions = vec![]; let mut using_forge = false; - for version in curseforge_mod.gameVersionLatestFiles { - let version_number : String = version.gameVersion.chars().skip(2).take(version.gameVersion.len()).collect(); + for version in curseforge_mod.game_version_latest_files { + let version_number: String = version + .game_version + .chars() + .skip(2) + .take(version.game_version.len()) + .collect(); if version_number.parse::().unwrap() < 14.0 { using_forge = true; } - mod_game_versions.push(version.gameVersion); + mod_game_versions.push(version.game_version); } let mut mod_categories = vec![]; @@ -218,7 +237,9 @@ pub async fn index_mods(conn : PgConnection) { "Technology" => mod_categories.push(String::from("technology")), "Processing" => mod_categories.push(String::from("technology")), "Player Transport" => mod_categories.push(String::from("technology")), - "Energy, Fluid, and Item Transport" => mod_categories.push(String::from("technology")), + "Energy, Fluid, and Item Transport" => { + mod_categories.push(String::from("technology")) + } "Food" => mod_categories.push(String::from("food")), "Farming" => mod_categories.push(String::from("food")), "Energy" => mod_categories.push(String::from("technology")), @@ -258,20 +279,20 @@ pub async fn index_mods(conn : PgConnection) { } let mut mod_attachments = curseforge_mod.attachments; - mod_attachments.retain(|x| x.isDefault); + mod_attachments.retain(|x| x.is_default); - if mod_attachments.len() == 0 { + if mod_attachments.is_empty() { mod_attachments.push(Attachment { url: "".to_string(), - isDefault: true + is_default: true, }) } - let mut latest_version = "None".to_string(); - - if mod_game_versions.len() > 0 { - latest_version = mod_game_versions[0].to_string(); - } + let latest_version = if !mod_game_versions.is_empty() { + mod_game_versions[0].to_string() + } else { + "None".to_string() + }; docs_to_add.push(SearchMod { mod_id: curseforge_mod.id, @@ -280,30 +301,32 @@ pub async fn index_mods(conn : PgConnection) { description: curseforge_mod.summary, keywords: mod_categories, versions: mod_game_versions.clone(), - downloads: curseforge_mod.downloadCount as i32, - page_url: curseforge_mod.websiteUrl, + downloads: curseforge_mod.download_count as i32, + page_url: curseforge_mod.website_url, icon_url: (mod_attachments[0].url).to_string(), author_url: (&curseforge_mod.authors[0].url).to_string(), - date_created: curseforge_mod.dateCreated.chars().take(10).collect(), - date_modified: curseforge_mod.dateModified.chars().take(10).collect(), - latest_version: latest_version, - empty: String::from("{}{}{}") + date_created: curseforge_mod.date_created.chars().take(10).collect(), + date_modified: curseforge_mod.date_modified.chars().take(10).collect(), + latest_version, + empty: String::from("{}{}{}"), }) } - mods_index.add_documents(docs_to_add, Some("mod_id")).unwrap(); + mods_index + .add_documents(docs_to_add, Some("mod_id")) + .unwrap(); //Write Settings let settings = mods_index.get_settings().unwrap(); - let mut ranking_rules = vec![ + let ranking_rules = vec![ "typo".to_string(), "words".to_string(), "proximity".to_string(), "attribute".to_string(), "wordsPosition".to_string(), "exactness".to_string(), - "desc(downloads)".to_string() + "desc(downloads)".to_string(), ]; let displayed_attributes = vec![ @@ -341,4 +364,4 @@ pub async fn index_mods(conn : PgConnection) { .with_ranking_rules(ranking_rules); mods_index.set_settings(&write_settings).unwrap(); -} \ No newline at end of file +} diff --git a/src/schema.rs b/src/schema.rs index aa0039f2..523e9514 100644 --- a/src/schema.rs +++ b/src/schema.rs @@ -27,7 +27,4 @@ table! { } } -allow_tables_to_appear_in_same_query!( - mods, - versions, -); +allow_tables_to_appear_in_same_query!(mods, versions,);