|
| 1 | +use std::{ |
| 2 | + cmp::Ordering, |
| 3 | + fmt, |
| 4 | + fs::{File, OpenOptions}, |
| 5 | + io::{self, Write}, |
| 6 | + path::Path, |
| 7 | + str::FromStr, |
| 8 | + time::Instant, |
| 9 | +}; |
| 10 | + |
| 11 | +use anyhow::Context as _; |
| 12 | +use chrono::{DateTime, Days, Months, Utc}; |
| 13 | +use clap::Parser as _; |
| 14 | +use mkenv::Env as _; |
| 15 | +use records_lib::{DbUrlEnv, time::Time}; |
| 16 | +use sea_orm::Database; |
| 17 | + |
| 18 | +mkenv::make_env! {AppEnv includes [DbUrlEnv as db_env]:} |
| 19 | + |
| 20 | +#[derive(Clone)] |
| 21 | +struct SinceDuration { |
| 22 | + date: DateTime<Utc>, |
| 23 | +} |
| 24 | + |
| 25 | +#[derive(Debug)] |
| 26 | +struct InvalidSinceDuration; |
| 27 | + |
| 28 | +impl fmt::Display for InvalidSinceDuration { |
| 29 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 30 | + f.write_str("invalid \"since duration\" argument") |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +impl std::error::Error for InvalidSinceDuration {} |
| 35 | + |
| 36 | +impl FromStr for SinceDuration { |
| 37 | + type Err = InvalidSinceDuration; |
| 38 | + |
| 39 | + fn from_str(s: &str) -> Result<Self, Self::Err> { |
| 40 | + let (n, unit) = s.split_at(s.len() - 1); |
| 41 | + let n = n.parse::<u32>().map_err(|_| InvalidSinceDuration)?; |
| 42 | + let now = Utc::now(); |
| 43 | + let date = match unit { |
| 44 | + "d" => now - Days::new(n as _), |
| 45 | + "w" => now - Days::new(n as u64 * 7), |
| 46 | + "m" => now - Months::new(n), |
| 47 | + "y" => now - Months::new(n * 12), |
| 48 | + _ => return Err(InvalidSinceDuration), |
| 49 | + }; |
| 50 | + Ok(Self { date }) |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +#[derive(clap::Parser)] |
| 55 | +struct Args { |
| 56 | + #[arg( |
| 57 | + short = 'p', |
| 58 | + long = "player-file", |
| 59 | + default_value = "player_ranking.csv" |
| 60 | + )] |
| 61 | + player_ranking_file: String, |
| 62 | + #[arg(short = 'm', long = "map-file", default_value = "map_ranking.csv")] |
| 63 | + map_ranking_file: String, |
| 64 | + #[arg(long = "since", value_parser = clap::value_parser!(SinceDuration))] |
| 65 | + from_date: Option<SinceDuration>, |
| 66 | +} |
| 67 | + |
| 68 | +fn open_file<P: AsRef<Path>>(path: P) -> io::Result<File> { |
| 69 | + OpenOptions::new() |
| 70 | + .write(true) |
| 71 | + .create(true) |
| 72 | + .truncate(true) |
| 73 | + .open(path) |
| 74 | +} |
| 75 | + |
| 76 | +#[tokio::main] |
| 77 | +async fn main() -> anyhow::Result<()> { |
| 78 | + let now = Instant::now(); |
| 79 | + |
| 80 | + dotenvy::dotenv().context("couldn't get environment file")?; |
| 81 | + let args = Args::parse(); |
| 82 | + |
| 83 | + let mut player_ranking_file = |
| 84 | + open_file(args.player_ranking_file).context("couldn't open player ranking output file")?; |
| 85 | + let mut map_ranking_file = |
| 86 | + open_file(args.map_ranking_file).context("couldn't open map ranking output file")?; |
| 87 | + |
| 88 | + player_ranking_file |
| 89 | + .write(b"id,login,name,score,player_link\n") |
| 90 | + .context("couldn't write header to player ranking file")?; |
| 91 | + map_ranking_file |
| 92 | + .write(b"id,map_uid,name,score,average_score,min_record,") |
| 93 | + .and_then(|_| { |
| 94 | + map_ranking_file |
| 95 | + .write(b"max_record,average_record,median_record,records_count,map_link\n") |
| 96 | + }) |
| 97 | + .context("couldn't write header to map ranking file")?; |
| 98 | + |
| 99 | + let db_url = AppEnv::try_get() |
| 100 | + .context("couldn't initialize environment")? |
| 101 | + .db_env |
| 102 | + .db_url; |
| 103 | + let db = Database::connect(db_url) |
| 104 | + .await |
| 105 | + .context("couldn't connect to database")?; |
| 106 | + |
| 107 | + println!( |
| 108 | + "Calculating scores{}...", |
| 109 | + match &args.from_date { |
| 110 | + Some(SinceDuration { date }) => format!(" since {}", date.format("%d/%m/%Y")), |
| 111 | + None => "".to_owned(), |
| 112 | + } |
| 113 | + ); |
| 114 | + |
| 115 | + let scores = player_map_ranking::compute_scores(&db, args.from_date.map(|d| d.date)) |
| 116 | + .await |
| 117 | + .context("couldn't compute the scores")?; |
| 118 | + |
| 119 | + println!("Sorting them..."); |
| 120 | + |
| 121 | + let mut player_ranking = scores.player_scores.into_iter().collect::<Vec<_>>(); |
| 122 | + player_ranking.sort_by(|(_, a), (_, b)| b.partial_cmp(a).unwrap_or(Ordering::Equal)); |
| 123 | + let mut map_ranking = scores.map_scores.into_iter().collect::<Vec<_>>(); |
| 124 | + map_ranking.sort_by(|(_, a), (_, b)| b.partial_cmp(a).unwrap_or(Ordering::Equal)); |
| 125 | + |
| 126 | + println!("Writing to files..."); |
| 127 | + |
| 128 | + for (player, score) in player_ranking { |
| 129 | + writeln!( |
| 130 | + player_ranking_file, |
| 131 | + "{},{login},{},{score},https://obstacle.titlepack.io/player/{login}", |
| 132 | + player.inner.id, |
| 133 | + player.inner.name, |
| 134 | + login = player.inner.login, |
| 135 | + ) |
| 136 | + .context("couldn't write a row to player ranking file")?; |
| 137 | + } |
| 138 | + |
| 139 | + for (map, score) in map_ranking { |
| 140 | + writeln!( |
| 141 | + map_ranking_file, |
| 142 | + "{},{map_uid},{},{score},{},{},{},{},{},{},https://obstacle.titlepack.io/map/{map_uid}", |
| 143 | + map.inner.id, |
| 144 | + map.inner.name, |
| 145 | + score / map.stats.records_count, |
| 146 | + map.stats.min_record, |
| 147 | + map.stats.max_record, |
| 148 | + map.stats.average_record, |
| 149 | + map.stats.median_record, |
| 150 | + map.stats.records_count, |
| 151 | + map_uid = map.inner.game_id, |
| 152 | + ) |
| 153 | + .context("couldn't write a row to map ranking file")?; |
| 154 | + } |
| 155 | + |
| 156 | + println!( |
| 157 | + "Finished. Time taken: {}", |
| 158 | + Time(now.elapsed().as_millis() as _) |
| 159 | + ); |
| 160 | + |
| 161 | + Ok(()) |
| 162 | +} |
0 commit comments