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
pub mod card;
pub mod fields;
pub use card::*;
use std::fs;
use std::io;
use std::io::Read;
use std::path::Path;
pub fn read_cards(source: &str) -> io::Result<Vec<String>> {
let path = Path::new(&source);
let mut raw = String::new();
if path.is_dir() {
for file in vcf_files(&path)? {
if let Some(s) = file.path().to_str() {
let content = read_file(s)?;
raw.push_str(&content);
}
}
} else if path.is_file() {
raw.push_str(&read_file(source)?);
}
let splits = raw
.split("BEGIN:VCARD")
.filter(|x| !x.is_empty())
.filter_map(|s| s.parse().ok())
.collect::<Vec<String>>();
Ok(splits)
}
pub fn read_file(path: &str) -> Result<String, io::Error> {
let mut s = String::new();
fs::File::open(path)?.read_to_string(&mut s)?;
Ok(s)
}
pub fn vcf_files(path: &Path) -> io::Result<Vec<fs::DirEntry>> {
let files = fs::read_dir(path)?
.filter_map(|f| f.ok())
.filter_map(|f| is_vcf(f))
.collect::<Vec<fs::DirEntry>>();
Ok(files)
}
fn is_vcf(file: fs::DirEntry) -> Option<fs::DirEntry> {
if let Some(extension) = file.path().extension() {
if let Some(ext) = extension.to_str() {
let lower_ext = String::from(ext).to_lowercase();
if lower_ext == "vcf" {
return Some(file);
}
}
}
None
}