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
extern crate custom_error;
use crate::ParserError::*;
use custom_error::custom_error;
use std::{fs::File, io::Read};

/// Mod struct. Stores the id, name, link and whether the mod is from the workshop or not
#[derive(Clone, PartialEq, Debug)]
pub struct Mod {
    pub id: i64,
    pub name: String,
    pub from_steam: bool,
    pub link: String,
}

/// Preset struct. Stores the preset name and a vector of all the mods
#[derive(PartialEq, Debug)]
pub struct Preset {
    pub name: String,
    pub mods: Vec<Mod>,
}

custom_error! {pub ParserError
    StringConvFail = "Failed to read file to string",
    DocParseErr = "Failed to parse document with error",
    DocReadErr = "Failed to read file from path",
    TagFindErr = "Unable to find necessary tags. Please check your preset is correctly exported"
}

impl Preset {
    /// This function returns a preset from a file object
    ///
    /// # Examples
    ///
    /// ```rust
    /// match std::fs::File::open(some_path) {
    ///     Ok(file) => {
    ///         match arma_preset_parser::Preset::from_file(file) {
    ///             Ok(preset) => println!("{:?}", preset),
    ///             Err(e) => println!("{}", e)
    ///         };
    ///     },
    ///     Err(e) => println!("{}", e)
    /// };
    /// ```
    pub fn from_file(file: File) -> Result<Self, ParserError> {
        parse(file)
    }

    /// This function returns a preset from a String filepath
    ///
    /// # Examples
    ///
    /// ```rust
    /// match arma_preset_parser::Preset::from_fs("some_path".parse().unwrap()) {
    ///     Ok(preset) => println!("{:?}", preset),
    ///     Err(e) => println!("{}", e)
    /// };
    /// ```
    pub fn from_fs(path: String) -> Result<Self, ParserError> {
        let file: File = match File::open(path) {
            Ok(f) => f,
            Err(_) => return Err(DocReadErr),
        };
        parse(file)
    }

    /// This function returns a vector of mods from a preset
    ///
    /// # Examples
    ///
    /// ```rust
    /// match arma_preset_parser::Preset::from_fs("some_path".parse().unwrap()) {
    ///     Ok(preset) => println!("{:?}", preset.as_mods()),
    ///     Err(e) => println!("{}", e)
    /// };
    /// ```
    pub fn as_mods(&self) -> Vec<Mod> {
        let mut vec = vec![];
        for _mod in &self.mods {
            vec.push(_mod.clone())
        }
        vec
    }

    /// This function returns a vector of mod ids from a preset
    ///
    /// # Examples
    ///
    /// ```rust
    /// match arma_preset_parser::Preset::from_fs("some_path".parse().unwrap()) {
    ///     Ok(preset) => println!("{:?}", preset.as_ids()),
    ///     Err(e) => println!("{}", e)
    /// };
    /// ```
    pub fn as_ids(&self) -> Vec<i64> {
        let mut vec = vec![];
        for _mod in &self.mods {
            vec.push(_mod.clone().id)
        }
        vec
    }

    /// This function returns a vector of mod names from a preset
    ///
    /// # Examples
    ///
    /// ```rust
    /// match arma_preset_parser::Preset::from_fs("some_path".parse().unwrap()) {
    ///     Ok(preset) => println!("{:?}", preset.as_names()),
    ///     Err(e) => println!("{}", e)
    /// };
    /// ```
    pub fn as_names(&self) -> Vec<String> {
        let mut vec = vec![];
        for _mod in &self.mods {
            vec.push(_mod.clone().name)
        }
        vec
    }

    /// This function returns a vector of mod names from a preset
    ///
    /// # Examples
    ///
    /// ```rust
    /// match arma_preset_parser::Preset::from_fs("some_path".parse().unwrap()) {
    ///     Ok(preset) => println!("{:?}", preset.as_links()),
    ///     Err(e) => println!("{}", e)
    /// };
    /// ```
    pub fn as_links(&self) -> Vec<String> {
        let mut vec = vec![];
        for _mod in &self.mods {
            vec.push(_mod.clone().link)
        }
        vec
    }
}

/// Actual parser for the preset. Constructed around the lovely roxmltree package
/// This function takes a file object as the input and presents the user with a Result containing both the preset and some custom error responses (see above)
/// This is an entirely internal function and as such does not contain any external-facing components
fn parse(mut file: File) -> Result<Preset, ParserError> {
    let mut contents: String = "".to_string();

    match file.read_to_string(&mut contents) {
        Ok(_) => {}
        Err(_) => return Err(StringConvFail),
    };

    match roxmltree::Document::parse(&contents) {
        Ok(doc) => {
            let mut preset: Preset = Preset {
                name: "".to_string(),
                mods: vec![],
            };
            let html_node = match doc.root().children().find(|n| n.has_tag_name("html")) {
                Some(n) => n,
                None => return Err(TagFindErr),
            };
            for node in html_node.children().filter(|n| n.is_element()) {
                if node.has_tag_name("head") {
                    let tag = match node.children().find(|n| {
                        n.has_tag_name("meta") && n.attribute("name") == Some("arma:PresetName")
                    }) {
                        Some(n) => n,
                        None => return Err(TagFindErr),
                    };
                    preset.name = tag.attribute("content").unwrap().parse().unwrap();
                } else if node.has_tag_name("body") {
                    let im1 = match node
                        .children()
                        .find(|n| n.has_tag_name("div") && n.attribute("class") == Some("mod-list"))
                    {
                        Some(n) => n,
                        None => return Err(TagFindErr),
                    };
                    let im2 = match im1.children().find(|n| n.has_tag_name("table")) {
                        Some(n) => n,
                        None => return Err(TagFindErr),
                    };
                    let im3 = im2.children().filter(|n| {
                        n.has_tag_name("tr") && n.attribute("data-type") == Some("ModContainer")
                    });
                    for mod_cont in im3 {
                        let mut temp_mod = Mod {
                            id: 0,
                            name: "".to_string(),
                            from_steam: false,
                            link: "".to_string(),
                        };
                        for item in mod_cont.children().filter(|n| n.is_element()) {
                            if item.has_attribute("data-type") {
                                temp_mod.name = match item.children().find(|n| n.is_text()) {
                                    Some(n) => n,
                                    None => return Err(TagFindErr),
                                }
                                .text()
                                .unwrap()
                                .parse()
                                .unwrap();
                            } else {
                                if item
                                    .children()
                                    .find(|n| n.attribute("class") == Some("from-steam"))
                                    .is_some()
                                {
                                    temp_mod.from_steam = true;
                                } else if item
                                    .children()
                                    .find(|n| n.attribute("class") == Some("from-local"))
                                    .is_some()
                                {
                                    temp_mod.from_steam = false;
                                } else {
                                    if item.children().find(|n| n.has_tag_name("a")).is_some() {
                                        temp_mod.link =
                                            match item.children().find(|n| n.has_tag_name("a")) {
                                                Some(n) => n,
                                                None => return Err(TagFindErr),
                                            }
                                            .attribute("href")
                                            .unwrap()
                                            .parse()
                                            .unwrap();
                                        temp_mod.id = temp_mod.link.replace("http://steamcommunity.com/sharedfiles/filedetails/?id=", "").parse().unwrap()
                                    } else {
                                        temp_mod.link = match item
                                            .children()
                                            .find(|n| n.has_tag_name("span"))
                                        {
                                            Some(n) => n,
                                            None => return Err(TagFindErr),
                                        }
                                        .attribute("data-meta")
                                        .unwrap()
                                        .parse()
                                        .unwrap();
                                    }
                                }
                            }
                        }
                        preset.mods.push(temp_mod);
                    }
                }
            }
            Ok(preset)
        }
        Err(_) => return Err(DocParseErr),
    }
}

#[cfg(test)]
mod tests {
    use crate::{parse, Mod, Preset};
    use std::fs::File;

    #[test]
    fn parse_file() {
        let preset = Preset {
            name: "Parser Test".parse().unwrap(),
            mods: vec![
                Mod {
                    id: 0,
                    name: "Ryan\'s ACE Canteen".parse().unwrap(),
                    from_steam: false,
                    link: "local:Ryan\'s ACE Canteen|@Ryan\'s ACE Canteen|"
                        .parse()
                        .unwrap(),
                },
                Mod {
                    id: 450814997,
                    name: "CBA_A3".parse().unwrap(),
                    from_steam: true,
                    link: "http://steamcommunity.com/sharedfiles/filedetails/?id=450814997"
                        .parse()
                        .unwrap(),
                },
                Mod {
                    id: 463939057,
                    name: "ace".parse().unwrap(),
                    from_steam: true,
                    link: "http://steamcommunity.com/sharedfiles/filedetails/?id=463939057"
                        .parse()
                        .unwrap(),
                },
            ],
        };
        assert_eq!(
            parse(File::open("tests\\samples\\Arma 3 Preset Parser Test.html").unwrap()).unwrap(),
            preset
        );
    }

    #[test]
    fn parse_from_fs() {
        let preset: Preset = Preset {
            name: "Parser Test".parse().unwrap(),
            mods: vec![
                Mod {
                    id: 0,
                    name: "Ryan\'s ACE Canteen".parse().unwrap(),
                    from_steam: false,
                    link: "local:Ryan\'s ACE Canteen|@Ryan\'s ACE Canteen|"
                        .parse()
                        .unwrap(),
                },
                Mod {
                    id: 450814997,
                    name: "CBA_A3".parse().unwrap(),
                    from_steam: true,
                    link: "http://steamcommunity.com/sharedfiles/filedetails/?id=450814997"
                        .parse()
                        .unwrap(),
                },
                Mod {
                    id: 463939057,
                    name: "ace".parse().unwrap(),
                    from_steam: true,
                    link: "http://steamcommunity.com/sharedfiles/filedetails/?id=463939057"
                        .parse()
                        .unwrap(),
                },
            ],
        };
        assert_eq!(
            Preset::from_fs(
                "tests\\samples\\Arma 3 Preset Parser Test.html"
                    .parse()
                    .unwrap()
            )
            .unwrap(),
            preset
        );
    }
    #[test]
    fn parse_from_file() {
        let preset: Preset = Preset {
            name: "Parser Test".parse().unwrap(),
            mods: vec![
                Mod {
                    id: 0,
                    name: "Ryan\'s ACE Canteen".parse().unwrap(),
                    from_steam: false,
                    link: "local:Ryan\'s ACE Canteen|@Ryan\'s ACE Canteen|"
                        .parse()
                        .unwrap(),
                },
                Mod {
                    id: 450814997,
                    name: "CBA_A3".parse().unwrap(),
                    from_steam: true,
                    link: "http://steamcommunity.com/sharedfiles/filedetails/?id=450814997"
                        .parse()
                        .unwrap(),
                },
                Mod {
                    id: 463939057,
                    name: "ace".parse().unwrap(),
                    from_steam: true,
                    link: "http://steamcommunity.com/sharedfiles/filedetails/?id=463939057"
                        .parse()
                        .unwrap(),
                },
            ],
        };
        assert_eq!(
            Preset::from_file(
                File::open("tests\\samples\\Arma 3 Preset Parser Test.html").unwrap()
            )
            .unwrap(),
            preset
        );
    }
}