use crate::error::{Error, Result};
use crate::model::{Credential, ItemKind, NewItem, Payload};
use crate::vault::Vault;
use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64;
use serde::{Deserialize, Serialize};
pub const EXPORT_VERSION: u32 = 1;
#[derive(Debug, Serialize, Deserialize)]
pub struct Export {
#[serde(rename = "sefy_export")]
pub version: u32,
pub items: Vec<ExportItem>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ExportItem {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub uuid: Option<String>,
pub title: String,
pub kind: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub tags: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub text: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub login: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub password: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub totp: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub notes: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub filename: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub bytes_base64: Option<String>,
}
pub fn export(vault: &Vault) -> Result<Export> {
let mut items = Vec::new();
for summary in vault.list()? {
let item = vault.get(summary.id)?;
let mut exported = ExportItem {
uuid: Some(item.summary.uuid),
title: item.summary.title,
kind: item.summary.kind.as_str().to_owned(),
tags: item.summary.tags,
text: None,
login: None,
password: None,
url: None,
totp: None,
notes: None,
filename: None,
bytes_base64: None,
};
match item.payload {
Payload::Note { text } => exported.text = Some(text),
Payload::Credential(credential) => {
exported.login = Some(credential.login);
exported.password = Some(credential.password);
exported.url = credential.url;
exported.totp = credential.totp;
exported.notes = credential.notes;
}
Payload::File { filename, bytes } => {
exported.filename = Some(filename);
exported.bytes_base64 = Some(BASE64.encode(&bytes));
}
}
items.push(exported);
}
Ok(Export {
version: EXPORT_VERSION,
items,
})
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ImportReport {
pub added: usize,
pub skipped: usize,
}
impl ImportReport {
pub fn total(&self) -> usize {
self.added + self.skipped
}
}
pub fn import(vault: &mut Vault, export: &Export) -> Result<ImportReport> {
if export.version != EXPORT_VERSION {
return Err(Error::UnsupportedExport(export.version));
}
let prepared: Vec<(Option<&str>, NewItem)> = export
.items
.iter()
.enumerate()
.map(|(index, item)| Ok((item.uuid.as_deref(), to_new_item(index, item)?)))
.collect::<Result<_>>()?;
let mut report = ImportReport::default();
for (uuid, item) in prepared {
match uuid {
Some(uuid) if vault.find_by_uuid(uuid)?.is_some() => report.skipped += 1,
Some(uuid) => {
let now = crate::vault::now();
vault.add_existing(item, uuid, now, now)?;
report.added += 1;
}
None => {
vault.add(item)?;
report.added += 1;
}
}
}
vault.save()?;
Ok(report)
}
fn to_new_item(index: usize, item: &ExportItem) -> Result<NewItem> {
let kind = ItemKind::parse(&item.kind).ok_or_else(|| Error::MalformedExport {
index,
reason: format!("unknown kind {:?}", item.kind),
})?;
let payload = match kind {
ItemKind::Note => Payload::Note {
text: item.text.clone().ok_or_else(|| Error::MalformedExport {
index,
reason: "a note needs a \"text\" field".to_owned(),
})?,
},
ItemKind::Credential => Payload::Credential(Credential {
login: item.login.clone().ok_or_else(|| Error::MalformedExport {
index,
reason: "a credential needs a \"login\" field".to_owned(),
})?,
password: item
.password
.clone()
.ok_or_else(|| Error::MalformedExport {
index,
reason: "a credential needs a \"password\" field".to_owned(),
})?,
url: item.url.clone(),
totp: item.totp.clone(),
notes: item.notes.clone(),
}),
ItemKind::File => {
let encoded = item
.bytes_base64
.as_deref()
.ok_or_else(|| Error::MalformedExport {
index,
reason: "a file needs a \"bytes_base64\" field".to_owned(),
})?;
Payload::File {
filename: item
.filename
.clone()
.ok_or_else(|| Error::MalformedExport {
index,
reason: "a file needs a \"filename\" field".to_owned(),
})?,
bytes: BASE64
.decode(encoded)
.map_err(|error| Error::MalformedExport {
index,
reason: format!("bytes_base64 is not valid base64: {error}"),
})?,
}
}
};
Ok(NewItem::new(item.title.clone(), payload).with_tags(item.tags.clone()))
}
pub fn to_json(export: &Export) -> Result<String> {
serde_json::to_string_pretty(export).map_err(|error| Error::UnreadableExport(error.to_string()))
}
pub fn from_json(json: &str) -> Result<Export> {
serde_json::from_str(json).map_err(|error| Error::UnreadableExport(error.to_string()))
}