mod acf; mod discord; mod steam; use crate::discord::{DiscordEmbedThumbnail, DiscordEmbeds, DiscordWebhook}; use crate::steam::{SteamApiResponse, WorkshopContent}; use acf::AppWorkshop; use anyhow::Result; use clap::Parser; use iter_chunks::IterChunks; use rand::{thread_rng, Rng}; use rayon::iter::{IntoParallelIterator, ParallelIterator}; use reqwest::header::USER_AGENT; use std::ops::Add; use std::path::PathBuf; use std::process::exit; use std::time::{Duration, SystemTime}; use tokio::time::sleep; use tracing::{error, info, warn}; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; #[derive(Parser, Debug)] #[command(author, version, about, long_about = None)] struct Args { #[arg(long, env("STEAM_WEB_KEY"), help("Steam web api key"))] steam_key: String, #[arg(long, env("DISCORD_WEBHOOK"))] acf_file: PathBuf, #[arg(long, env("DISCORD_WEBHOOK"), requires("user_agent"), help("Pass in a discord webhook to enable discord support, you must also set header_info. Only pass in everything after 'https://discord.com/api/webhooks/'"))] discord_key: Option, #[arg( long, env("DISCORD_USERNAME"), requires("discord_key"), help("Set the discord webhook username") )] discord_name: Option, #[arg( long, env("DISCORD_PFP"), requires("discord_key"), help("Set the discord webhook profile picture.") )] discord_pfp: Option, #[arg(long, env("USER_AGENT"), help("Required if using discord for changelog support, format it such as `Wrench - email@email.com` so people can reach out if need be"))] user_agent: Option, } #[tokio::main] async fn main() -> Result<()> { tracing_subscriber::registry() .with( tracing_subscriber::EnvFilter::try_from_default_env() .unwrap_or_else(|_| "wrench=info".into()), ) .with(tracing_subscriber::fmt::layer()) .init(); let args = Args::parse(); let acf = AppWorkshop::new(&args.acf_file)?; let calls = (acf.workshop_items_installed.len() as f64 / 200.0).ceil() as usize; info!( "Found {} mods, this will be batched into {} requests.", acf.workshop_items_installed.len(), calls ); let res: SteamApiResponse = { let mut response = SteamApiResponse::default(); let mut chunks = acf.workshop_items_installed.iter().chunks(200); let mut request_count = 1; while let Some(chunk) = chunks.next() { let workshop = { let mut total = String::new(); for (pos, map) in chunk.enumerate() { total.push_str(format!("&publishedfileids%5B{}%5D={}", pos, map.0).as_str()); } total }; let url = format!("https://api.steampowered.com/IPublishedFileService/GetDetails/v1/?key={}{}&short_description=true&includeforsaledata=false&includemetadata=false&appid=108600&strip_description_bbcode=true", args.steam_key, workshop); info!("Sending steam request {}", request_count); request_count += 1; let client = reqwest::ClientBuilder::new() .gzip(true) .brotli(true) .build()?; let result = client.get(&url).send().await; if let Err(why) = result { error!("Calling steam resulted in an error, check your key or try again later, {why}, {url}"); exit(1); } let body = result?.text().await?; let res = serde_json::from_str::(&body); if let Err(why) = res { error!("Parsing body to SteamApiResponse failed, {why}, {url}"); exit(1); } let mut res = res?; response .response .published_file_details .append(&mut res.response.published_file_details); } response }; let mut update_list: Vec = res.response.published_file_details.clone().into_par_iter() .filter(|details| { if details.title.is_none() { error!("Workshop mod {} has been removed from the workshop, you must manually remove this mod", details.published_file_id); return false; } let item = acf.workshop_items_installed.get(&details.published_file_id); if item.is_none() { warn!("{} somehow does not exist in our acf but was returned by steam (skipping)", details.published_file_id); return false; } if let Some(time) = details.time_updated { let timestamp = item.unwrap().time_updated.unwrap(); if time > timestamp { if let Some(title) = &details.title { warn!("{} needs updating!", title); } else { warn!("{} needs updating (could not fetch title)", details.published_file_id); } return true; } } false }).collect(); if update_list.is_empty() { info!("No mods need updating"); exit(1); } if args.discord_key.is_none() { return Ok(()); } let webhook = args.discord_key.unwrap(); let time = SystemTime::now() .add(Duration::from_secs(60 * 5)) .duration_since(SystemTime::UNIX_EPOCH)? .as_secs(); let mut rng = thread_rng(); let sounds = { // TODO: Cleanup, could not pass rng without fighting the compiler let prefix = random_sound(rng.gen_range(0..6)); let postfix = random_sound(rng.gen_range(0..6)); (prefix, postfix) }; // We can only have a max of 10 embeds, so skip the rest let update_count = update_list.len(); let grammar = if update_count > 1 { "mods" } else { "mod" }; update_list.truncate(10); let content = format!( "{} The server is due to restart at , {} {} have been updated: {}", sounds.0, update_count, grammar, sounds.1 ); let header = &args.user_agent.unwrap_or_default(); for update in update_list.iter_mut() { for _ in 0..3 { let result = fetch_changelog(&update.published_file_id.to_string(), header).await; if let Ok(changelog) = result { update.changelog = changelog; break; } else if let Err(retry) = result { if !retry { break; } warn!("Could not fetch changelog, sleeping for 5 seconds before trying"); sleep(Duration::from_secs(5)).await; } } if update.changelog.is_empty() { update.changelog = "Change log was either not provided or could not be fetched".into(); } sleep(Duration::from_secs(5)).await; } let embeds = update_list .into_iter() .map(|update_list| DiscordEmbeds { title: update_list.title.unwrap(), color: { let n: u16 = rng.gen(); n.to_string() }, thumbnail: DiscordEmbedThumbnail { url: update_list.preview_url.unwrap(), }, url: format!( "https://steamcommunity.com/sharedfiles/filedetails/?id={}", update_list.published_file_id ), description: update_list.changelog, }) .collect(); let pfp = args .discord_pfp .unwrap_or("https://i.imgur.com/mXpcHBX.png".into()); let name = args.discord_name.unwrap_or("Server maid".into()); let msg: DiscordWebhook = DiscordWebhook { avatar_url: pfp.as_str(), username: name.as_str(), content: content.as_str(), embeds, }; info!("Sending discord web hook"); let client = reqwest::Client::new(); client.post(webhook).json(&msg).send().await?; Ok(()) } fn random_sound(rng: u8) -> &'static str { match rng { 1 => "", 2 => "", 3 => "", 4 => "", 0 | _ => "", } } // TODO: Redo, messy, not nice to use // TODO: Return an actual error, and a enum saying if we should retry or not // TODO: Retrys should be handled in here async fn fetch_changelog(id: &String, header: &String) -> std::result::Result { let client = reqwest::ClientBuilder::new(); let client = client.gzip(true).brotli(true).build(); if let Err(why) = client { error!("Could not build reqwest client for changelog {id}, {why}"); return Err(false); } let req = client .unwrap() .get(format!( "https://steamcommunity.com/sharedfiles/filedetails/changelog/{id}" )) .header(USER_AGENT, header) .send() .await; if let Err(why) = req { error!("Could not do changelog request for {id}, {why}"); return Err(false); } let req = req.unwrap(); if req.status() != 200 { error!( "Status for {id} was {}, reason: {:?}", req.status(), req.error_for_status() ); return Err(true); } let text = req.text().await.expect("Could not convert text to utf8"); let text = text.as_str(); // Should probably print here? But if text is that big, that's just silly if text.len() > u32::MAX as usize { tracing::error!( "Text body bigger then {}, body was {}. Can not be parsed by tl.", u32::MAX, text ); return Err(true); } let dom = tl::parse(text, tl::ParserOptions::default()).unwrap(); let parser = dom.parser(); let latest_cl = dom .query_selector(".workshopAnnouncement") .and_then(|mut iter| iter.next()); // Retry, since we most likely got an error page if latest_cl.is_none() { error!("Could not find .workshopAnnouncement for id {id}, response was {text}"); return Err(true); } let content = latest_cl.unwrap().get(parser).unwrap(); let p = content .as_tag() .unwrap() .query_selector(parser, "p") .and_then(|mut iter| iter.next()); // This really should not happen, since .workshopAnnouncement was found.. if p.is_none() { tracing::error!("Could not find p tag for id {id}, response was {text}"); return Err(false); } let text = p.unwrap().get(parser).unwrap().inner_html(parser); if text.is_empty() { error!("Mod {id} has no changelog, p tag is empty"); return Err(false); } Ok(text .replace("*", "\\*") .replace("

", "\n") .replace("
", "\n") .replace("", "\n")) }