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
}