use async_trait::async_trait;
use serde::Deserialize;
use sos_core::crypto::AccessKey;
use sos_vault::Vault;
use sos_vfs as vfs;
use std::path::{Path, PathBuf};
use tokio::io::AsyncRead;
use url::Url;
use super::{
GenericCsvConvert, GenericCsvEntry, GenericNoteRecord,
GenericPasswordRecord, UNTITLED,
};
use crate::{import::read_csv_records, Convert, Result};
const TYPE_LOGIN: &str = "login";
const TYPE_NOTE: &str = "note";
#[derive(Deserialize)]
pub struct BitwardenPasswordRecord {
pub folder: String,
pub favorite: String,
#[serde(rename = "type")]
pub kind: String,
pub name: String,
pub notes: String,
pub fields: String,
pub reprompt: String,
pub login_uri: Option<Url>,
pub login_username: String,
pub login_password: String,
pub login_totp: String,
}
impl From<BitwardenPasswordRecord> for GenericPasswordRecord {
fn from(value: BitwardenPasswordRecord) -> Self {
let label = if value.name.is_empty() {
UNTITLED.to_owned()
} else {
value.name
};
let note = if !value.notes.is_empty() {
Some(value.notes)
} else {
None
};
let url = if let Some(uri) = value.login_uri {
vec![uri]
} else {
vec![]
};
Self {
label,
url,
username: value.login_username,
password: value.login_password,
otp_auth: None,
tags: None,
note,
}
}
}
impl From<BitwardenPasswordRecord> for GenericNoteRecord {
fn from(value: BitwardenPasswordRecord) -> Self {
let label = if value.name.is_empty() {
UNTITLED.to_owned()
} else {
value.name
};
Self {
label,
text: value.notes,
tags: None,
note: None,
}
}
}
impl From<BitwardenPasswordRecord> for GenericCsvEntry {
fn from(value: BitwardenPasswordRecord) -> Self {
if value.kind == TYPE_LOGIN {
Self::Password(value.into())
} else {
Self::Note(value.into())
}
}
}
pub async fn parse_reader<R: AsyncRead + Unpin + Send>(
reader: R,
) -> Result<Vec<BitwardenPasswordRecord>> {
read_csv_records::<BitwardenPasswordRecord, _>(reader).await
}
pub async fn parse_path<P: AsRef<Path>>(
path: P,
) -> Result<Vec<BitwardenPasswordRecord>> {
parse_reader(vfs::File::open(path).await?).await
}
pub struct BitwardenCsv;
#[async_trait]
impl Convert for BitwardenCsv {
type Input = PathBuf;
async fn convert(
&self,
source: Self::Input,
vault: Vault,
key: &AccessKey,
) -> crate::Result<Vault> {
let records: Vec<GenericCsvEntry> = parse_path(source)
.await?
.into_iter()
.filter(|record| {
record.kind == TYPE_LOGIN || record.kind == TYPE_NOTE
})
.map(|r| r.into())
.collect();
GenericCsvConvert.convert(records, vault, key).await
}
}