use std::path::{Path, PathBuf};
use base64::{engine::general_purpose::STANDARD, Engine};
use bytes::Bytes;
use crate::error::SdkError;
pub enum AttachmentSource {
Bytes(Bytes),
Base64(String),
Path(PathBuf),
}
impl AttachmentSource {
pub async fn into_bytes(self) -> Result<Bytes, SdkError> {
match self {
AttachmentSource::Bytes(b) => Ok(b),
AttachmentSource::Base64(s) => {
let decoded = STANDARD
.decode(s.trim())
.map_err(|e| SdkError::Base64(e.to_string()))?;
Ok(Bytes::from(decoded))
}
AttachmentSource::Path(path) => {
let data = tokio::fs::read(&path).await?;
Ok(Bytes::from(data))
}
}
}
}
impl From<Bytes> for AttachmentSource {
fn from(b: Bytes) -> Self {
AttachmentSource::Bytes(b)
}
}
impl From<Vec<u8>> for AttachmentSource {
fn from(v: Vec<u8>) -> Self {
AttachmentSource::Bytes(Bytes::from(v))
}
}
impl From<&[u8]> for AttachmentSource {
fn from(s: &[u8]) -> Self {
AttachmentSource::Bytes(Bytes::copy_from_slice(s))
}
}
impl From<String> for AttachmentSource {
fn from(s: String) -> Self {
AttachmentSource::Base64(s)
}
}
impl From<&str> for AttachmentSource {
fn from(s: &str) -> Self {
AttachmentSource::Base64(s.to_owned())
}
}
impl From<PathBuf> for AttachmentSource {
fn from(p: PathBuf) -> Self {
AttachmentSource::Path(p)
}
}
impl From<&Path> for AttachmentSource {
fn from(p: &Path) -> Self {
AttachmentSource::Path(p.to_owned())
}
}