Something went wrong. Try again.
Project Zomboid workshop update cli checker, designed to be used in bash scripts (old and ugly code)
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358mod 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<String>,
#[arg( long, env("DISCORD_USERNAME"), requires("discord_key"), help("Set the discord webhook username") )] discord_name: Option<String>,
#[arg( long, env("DISCORD_PFP"), requires("discord_key"), help("Set the discord webhook profile picture.") )] discord_pfp: Option<String>,
#[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<String>,}
#[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::<SteamApiResponse>(&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<WorkshopContent> = 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 <t:{time:?}>, {} {} 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 => "<wzzt>", 2 => "<kzzt>", 3 => "<fzzt>", 4 => "<szzt>", 0 | _ => "<bzzt>", }}
// 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 hereasync fn fetch_changelog(id: &String, header: &String) -> std::result::Result<String, bool> { 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("<br></br>", "\n") .replace("<br>", "\n") .replace("<br\\>", "\n"))}