aboutsummaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 22d1ab4bbe8e9627f639c45b9ecd833fe6e37dde (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
extern crate structopt;
#[macro_use]
extern crate quick_error;
extern crate chrono;
extern crate colored;
extern crate evtclib;
extern crate humantime;
extern crate num_traits;
extern crate rayon;
extern crate regex;
extern crate walkdir;

use std::fs::File;
use std::io::{self, BufReader};
use std::path::PathBuf;
use std::str::FromStr;

use chrono::{Duration, NaiveDateTime};
use num_traits::cast::FromPrimitive;
use regex::Regex;
use structopt::StructOpt;
use walkdir::{DirEntry, WalkDir};

use evtclib::{AgentKind, AgentName, EventKind, Log};

mod errors;
use errors::RuntimeError;

mod output;

mod filters;

macro_rules! unwrap {
    ($p:pat = $e:expr => { $r:expr} ) => {
        if let $p = $e {
            $r
        } else {
            panic!("Pattern match failed!");
        }
    };
}

macro_rules! debug {
    ($($arg:tt)*) => {
        if debug_enabled() {
            use std::io::Write;
            let stderr = ::std::io::stderr();
            let mut lock = stderr.lock();
            write!(lock, "[d] ");
            writeln!(lock, $($arg)*);
        }
    }
}

static mut DEBUG_ENABLED: bool = false;

/// Return whether or not debug output should be enabled.
#[inline]
fn debug_enabled() -> bool {
    unsafe { DEBUG_ENABLED }
}

/// A program that allows you to search through all your evtc logs for specific
/// people.
#[derive(StructOpt, Debug)]
#[structopt(name = "raidgrep")]
pub struct Opt {
    /// Path to the folder with logs.
    #[structopt(
        short = "d",
        long = "dir",
        default_value = ".",
        parse(from_os_str)
    )]
    path: PathBuf,

    /// The fields which should be searched.
    #[structopt(short = "f", long = "fields", default_value = "all")]
    field: SearchField,

    /// Only display fights with the given outcome.
    #[structopt(short = "o", long = "outcome")]
    outcome: Option<FightOutcome>,

    /// Disable colored output.
    #[structopt(long = "no-color")]
    no_color: bool,

    /// Only show logs that are younger than the given time.
    #[structopt(
        short = "a",
        long = "younger",
        parse(try_from_str = "parse_time_arg")
    )]
    after: Option<NaiveDateTime>,

    /// Only show logs that are older than the given time.
    #[structopt(
        short = "b",
        long = "older",
        parse(try_from_str = "parse_time_arg")
    )]
    before: Option<NaiveDateTime>,

    /// Print more debugging information to stderr.
    #[structopt(long = "debug")]
    debug: bool,

    /// The regular expression to search for.
    #[structopt(name = "EXPR")]
    expression: Regex,
}

/// A flag indicating which fields should be searched.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum SearchField {
    /// Search all fields.
    All,
    /// Only search the account name.
    Account,
    /// Only search the character name.
    Character,
}

impl SearchField {
    /// True if the state says that the account name should be searched.
    #[inline]
    fn search_account(self) -> bool {
        self == SearchField::All || self == SearchField::Account
    }

    /// True if the state says that the character name should be searched.
    #[inline]
    fn search_character(self) -> bool {
        self == SearchField::All || self == SearchField::Character
    }
}

impl FromStr for SearchField {
    type Err = &'static str;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "all" => Ok(SearchField::All),
            "account" => Ok(SearchField::Account),
            "character" => Ok(SearchField::Character),
            _ => Err("Must be all, account or character"),
        }
    }
}

/// A log that matches the search criteria.
#[derive(Debug, Clone)]
pub struct LogResult {
    /// The path to the log file.
    log_file: PathBuf,
    /// The time of the recording.
    time: NaiveDateTime,
    /// The name of the boss.
    boss_name: String,
    /// A vector of all participating players.
    players: Vec<Player>,
    /// The outcome of the fight.
    outcome: FightOutcome,
}

/// A player.
#[derive(Debug, Clone)]
pub struct Player {
    /// Account name of the player.
    account_name: String,
    /// Character name of the player.
    character_name: String,
    /// Profession (or elite specialization) as english name.
    profession: String,
    /// Subsquad that the player was in.
    subgroup: u8,
}

/// Outcome of the fight.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FightOutcome {
    Success,
    Wipe,
}

impl FromStr for FightOutcome {
    type Err = &'static str;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "success" | "kill" => Ok(FightOutcome::Success),
            "wipe" | "fail" => Ok(FightOutcome::Wipe),
            _ => Err("Must be success or wipe"),
        }
    }
}

fn parse_time_arg(input: &str) -> Result<NaiveDateTime, &'static str> {
    if let Ok(duration) = humantime::parse_duration(input) {
        let now = chrono::Local::now().naive_local();
        let chrono_dur = Duration::from_std(duration).expect("Duration out of range!");
        return Ok(now - chrono_dur);
    }
    if let Ok(time) = humantime::parse_rfc3339_weak(input) {
        let timestamp = time
            .duration_since(std::time::SystemTime::UNIX_EPOCH)
            .unwrap()
            .as_secs();
        return Ok(NaiveDateTime::from_timestamp(timestamp as i64, 0));
    }
    Err("unknown time format")
}

fn main() {
    let opt = Opt::from_args();

    if opt.no_color {
        colored::control::set_override(false);
    }

    if opt.debug {
        // We haven't started any threads here yet, so this is fine.
        unsafe { DEBUG_ENABLED = true };
    }

    let result = grep(&opt);
    match result {
        Ok(_) => {}
        Err(e) => {
            eprintln!("Error: {}", e);
        }
    }
}

/// Check if the given entry represents a log file, based on the file name.
fn is_log_file(entry: &DirEntry) -> bool {
    entry
        .file_name()
        .to_str()
        .map(|n| n.ends_with(".evtc") || n.ends_with(".evtc.zip"))
        .unwrap_or(false)
}

/// Run the grep search with the given options.
fn grep(opt: &Opt) -> Result<(), RuntimeError> {
    rayon::scope(|s| {
        let walker = WalkDir::new(&opt.path);
        for entry in walker {
            let entry = entry?;
            s.spawn(move |_| {
                if is_log_file(&entry) {
                    if let Some(result) = search_log(&entry, opt).unwrap() {
                        output::colored(io::stdout(), &result).unwrap();
                    }
                }
            });
        }
        Ok(())
    })
}

/// Search the given single log.
///
/// If the log matches, returns `Ok(Some(..))`.
/// If the log doesn't match, returns `Ok(None)`.
/// If there was a fatal error, returns `Err(..)`.
fn search_log(entry: &DirEntry, opt: &Opt) -> Result<Option<LogResult>, RuntimeError> {
    let mut input = BufReader::new(File::open(entry.path())?);
    let raw = if entry
        .file_name()
        .to_str()
        .map(|n| n.ends_with(".zip"))
        .unwrap_or(false)
    {
        evtclib::raw::parse_zip(&mut input)
    } else {
        evtclib::raw::parse_file(&mut input)
    };
    let parsed = raw.ok().and_then(|m| evtclib::process(&m).ok());
    let log = if let Some(e) = parsed {
        e
    } else {
        debug!("log file cannot be parsed: {:?}", entry.path());
        return Ok(None);
    };

    let info = extract_info(entry, &log);

    let take_log = filters::filter_name(&log, opt)
        && filters::filter_outcome(&info, opt)
        && filters::filter_time(&info, opt);

    if take_log {
        Ok(Some(info))
    } else {
        Ok(None)
    }
}

/// Extract human-readable information from the given log file.
fn extract_info(entry: &DirEntry, log: &Log) -> LogResult {
    let boss_name = get_encounter_name(log)
        .unwrap_or_else(|| {
            debug!(
                "log file has unknown boss: {:?} (id: {:#x})",
                entry.path(),
                log.boss_id()
            );
            "unknown"
        }).into();

    let mut players = log
        .players()
        .map(|p| {
            unwrap! { AgentKind::Player { profession, elite } = p.kind() => {
            unwrap! { AgentName::Player {
                account_name,
                character_name,
                subgroup,
            } = p.name() =>
            {
                Player {
                    account_name: account_name.clone(),
                    character_name: character_name.clone(),
                    profession: get_profession_name(*profession, *elite).into(),
                    subgroup: *subgroup,
                }
            }}}}
        }).collect::<Vec<Player>>();
    players.sort_by_key(|p| p.subgroup);

    LogResult {
        log_file: entry.path().to_path_buf(),
        time: NaiveDateTime::from_timestamp(i64::from(get_start_timestamp(log)), 0),
        boss_name,
        players,
        outcome: get_fight_outcome(log),
    }
}

/// Get the timestamp of the log start time.
fn get_start_timestamp(log: &Log) -> u32 {
    for event in log.events() {
        if let EventKind::LogStart {
            local_timestamp, ..
        } = event.kind
        {
            return local_timestamp;
        }
    }
    0
}

/// Get the outcome of the fight.
fn get_fight_outcome(log: &Log) -> FightOutcome {
    for event in log.events() {
        if let EventKind::Reward { .. } = event.kind {
            return FightOutcome::Success;
        }
    }
    FightOutcome::Wipe
}

/// Get the (english) name for the given encounter
fn get_encounter_name(log: &Log) -> Option<&'static str> {
    use evtclib::statistics::gamedata::Boss;
    let boss = Boss::from_u16(log.boss_id())?;
    Some(match boss {
        Boss::ValeGuardian => "Vale Guardian",
        Boss::Gorseval => "Gorseval",
        Boss::Sabetha => "Sabetha",

        Boss::Slothasor => "Slothasor",
        Boss::Matthias => "Matthias",

        Boss::KeepConstruct => "Keep Construct",
        Boss::Xera => "Xera",

        Boss::Cairn => "Cairn",
        Boss::MursaatOverseer => "Mursaat Overseer",
        Boss::Samarog => "Samarog",
        Boss::Deimos => "Deimos",

        Boss::SoullessHorror => "Desmina",
        Boss::Dhuum => "Dhuum",

        Boss::ConjuredAmalgamate => "Conjured Amalgamate",
        Boss::LargosTwins => "Largos Twins",
        Boss::Qadim => "Qadim",

        Boss::Skorvald => "Skorvald",
        Boss::Artsariiv => "Artsariiv",
        Boss::Arkk => "Arkk",

        Boss::MAMA => "MAMA",
        Boss::Siax => "Siax the Corrupted",
        Boss::Ensolyss => "Ensolyss of the Endless Torment",
    })
}

/// Get the (english) name for the given profession/elite specialization.
fn get_profession_name(profession: u32, elite: u32) -> &'static str {
    match (profession, elite) {
        (1, 0) => "Guardian",
        (2, 0) => "Warrior",
        (3, 0) => "Engineer",
        (4, 0) => "Ranger",
        (5, 0) => "Thief",
        (6, 0) => "Elementalist",
        (7, 0) => "Mesmer",
        (8, 0) => "Necromancer",
        (9, 0) => "Revenant",

        (1, 27) => "Dragonhunter",
        (2, 18) => "Berserker",
        (3, 43) => "Scrapper",
        (4, 5) => "Druid",
        (5, 7) => "Daredevil",
        (6, 48) => "Tempest",
        (7, 40) => "Chronomancer",
        (8, 34) => "Reaper",
        (9, 52) => "Herald",

        (1, 62) => "Firebrand",
        (2, 61) => "Spellbreaker",
        (3, 57) => "Holosmith",
        (4, 55) => "Soulbeast",
        (5, 58) => "Deadeye",
        (6, 56) => "Weaver",
        (7, 59) => "Mirage",
        (8, 60) => "Scourge",
        (9, 63) => "Renegade",

        _ => {
            debug!("Unknown spec (prof: {}, elite: {})", profession, elite);
            "Unknown"
        }
    }
}