aboutsummaryrefslogtreecommitdiff
path: root/src/main.rs
blob: c776336f42084d2bf0a09e7a32058f8d24eac564 (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
extern crate structopt;
#[macro_use]
extern crate quick_error;
extern crate chrono;
extern crate colored;
extern crate evtclib;
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::NaiveDateTime;
use regex::Regex;
use structopt::StructOpt;
use walkdir::{DirEntry, WalkDir};

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

mod errors;
use errors::RuntimeError;

mod output;

#[derive(StructOpt, Debug)]
#[structopt(name = "raidgrep")]
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.
    /// Possible values: all, account, character
    #[structopt(short = "f", long = "fields", default_value = "all")]
    field: SearchField,

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

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum SearchField {
    All,
    Account,
    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"),
        }
    }
}

#[derive(Debug, Clone)]
pub struct LogResult {
    log_file: PathBuf,
    time: NaiveDateTime,
    boss_name: String,
    players: Vec<Player>,
}

#[derive(Debug, Clone)]
pub struct Player {
    account_name: String,
    character_name: String,
    profession: String,
    subgroup: u8,
}

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

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)
}

fn grep(opt: &Opt) -> Result<(), RuntimeError> {
    let walker = WalkDir::new(&opt.path);
    for entry in walker {
        let entry = entry?;
        if is_log_file(&entry) {
            if let Some(result) = search_log(&entry, opt)? {
                output::colored(io::stdout(), &result)?;
            }
        }
    }

    Ok(())
}

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 {
        return Ok(None);
    };

    for player in log.players() {
        match player.name() {
            AgentName::Player {
                account_name,
                character_name,
                ..
            } => {
                if ((opt.field == SearchField::All || opt.field == SearchField::Account)
                    && opt.expression.is_match(account_name))
                    || ((opt.field == SearchField::All || opt.field == SearchField::Character)
                        && opt.expression.is_match(character_name))
                {
                    return Ok(Some(extract_info(entry, &log)));
                }
            }
            _ => unreachable!(),
        }
    }

    Ok(None)
}

fn extract_info(entry: &DirEntry, log: &Log) -> LogResult {
    let boss_name = match log.boss().name() {
        AgentName::Single(s) => s,
        _ => "<unknown>",
    }.into();

    let mut players = log
        .players()
        .map(|p| {
            if let AgentKind::Player { profession, elite } = p.kind() {
                if let 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,
                    }
                } else {
                    unreachable!()
                }
            } else {
                unreachable!()
            }
        }).collect::<Vec<Player>>();
    players.sort_by_key(|p| p.subgroup);

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

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

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",

        _ => "Unknown",
    }
}