use std::fmt;
use std::path::{Path, PathBuf};
use bytes::Bytes;
use tokio::io::AsyncRead;
use crate::models::{Document, VersionRef};
pub struct FileInput {
pub(crate) source: Source,
pub(crate) filename: Option<String>,
pub(crate) content_type: Option<String>,
pub(crate) sha256: Option<String>,
}
pub(crate) enum Source {
Path(PathBuf),
Bytes(Bytes),
File {
file: tokio::fs::File,
size: Option<u64>,
},
Reader {
reader: Box<dyn AsyncRead + Send + Unpin>,
size: u64,
},
Document(VersionRef),
}
impl fmt::Debug for FileInput {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let source = match &self.source {
Source::Path(path) => format!("Path({})", path.display()),
Source::Bytes(bytes) => format!("Bytes({} bytes)", bytes.len()),
Source::File { size, .. } => format!("File({size:?} bytes)"),
Source::Reader { size, .. } => format!("Reader({size} bytes)"),
Source::Document(reference) => format!("Document({})", reference.document_id),
};
f.debug_struct("FileInput")
.field("source", &source)
.field("filename", &self.filename)
.field("content_type", &self.content_type)
.finish()
}
}
impl FileInput {
fn new(source: Source, filename: Option<String>) -> Self {
FileInput {
source,
filename,
content_type: None,
sha256: None,
}
}
pub fn path(path: impl AsRef<Path>) -> Self {
Self::new(Source::Path(path.as_ref().to_path_buf()), None)
}
pub fn bytes(data: impl Into<Bytes>, filename: impl Into<String>) -> Self {
Self::new(Source::Bytes(data.into()), Some(filename.into()))
}
pub fn file(file: tokio::fs::File, filename: impl Into<String>) -> Self {
Self::new(Source::File { file, size: None }, Some(filename.into()))
}
pub fn reader(
reader: impl AsyncRead + Send + Unpin + 'static,
size: u64,
filename: impl Into<String>,
) -> Self {
Self::new(
Source::Reader {
reader: Box::new(reader),
size,
},
Some(filename.into()),
)
}
pub fn document(document_id: impl Into<String>) -> Self {
Self::new(
Source::Document(VersionRef {
document_id: document_id.into(),
version_id: None,
}),
None,
)
}
pub fn version(document_id: impl Into<String>, version_id: impl Into<String>) -> Self {
Self::new(
Source::Document(VersionRef {
document_id: document_id.into(),
version_id: Some(version_id.into()),
}),
None,
)
}
pub fn with_filename(mut self, filename: impl Into<String>) -> Self {
self.filename = Some(filename.into());
self
}
pub fn with_content_type(mut self, content_type: impl Into<String>) -> Self {
self.content_type = Some(content_type.into());
self
}
pub fn with_sha256(mut self, sha256: impl Into<String>) -> Self {
self.sha256 = Some(sha256.into());
self
}
pub fn is_document(&self) -> bool {
matches!(self.source, Source::Document(_))
}
pub(crate) fn resolved_filename(&self) -> String {
if let Some(name) = &self.filename {
return name.clone();
}
match &self.source {
Source::Path(path) => path
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_else(|| "upload".into()),
_ => "upload".into(),
}
}
pub(crate) fn resolved_content_type(&self) -> String {
self.content_type
.clone()
.unwrap_or_else(|| crate::util::content_type_for(&self.resolved_filename()).to_owned())
}
pub(crate) fn stem(&self) -> Option<String> {
match &self.source {
Source::Document(_) => None,
_ => {
let name = self.resolved_filename();
Some(
name.rsplit_once('.')
.map(|(stem, _)| stem.to_owned())
.unwrap_or(name),
)
}
}
}
}
impl From<&str> for FileInput {
fn from(path: &str) -> Self {
FileInput::path(path)
}
}
impl From<String> for FileInput {
fn from(path: String) -> Self {
FileInput::path(path)
}
}
impl From<&String> for FileInput {
fn from(path: &String) -> Self {
FileInput::path(path)
}
}
impl From<&Path> for FileInput {
fn from(path: &Path) -> Self {
FileInput::path(path)
}
}
impl From<PathBuf> for FileInput {
fn from(path: PathBuf) -> Self {
FileInput::path(path)
}
}
impl From<&PathBuf> for FileInput {
fn from(path: &PathBuf) -> Self {
FileInput::path(path)
}
}
impl From<&Document> for FileInput {
fn from(document: &Document) -> Self {
match document.current_version_id() {
Some(version) => FileInput::version(document.id.clone(), version),
None => FileInput::document(document.id.clone()),
}
}
}
impl From<Document> for FileInput {
fn from(document: Document) -> Self {
FileInput::from(&document)
}
}
impl From<VersionRef> for FileInput {
fn from(reference: VersionRef) -> Self {
FileInput::new(Source::Document(reference), None)
}
}
#[derive(Debug, Default)]
pub struct ToolInput {
pub(crate) files: Vec<FileInput>,
}
impl ToolInput {
pub fn many<I, F>(files: I) -> Self
where
I: IntoIterator<Item = F>,
F: Into<FileInput>,
{
ToolInput {
files: files.into_iter().map(Into::into).collect(),
}
}
pub fn len(&self) -> usize {
self.files.len()
}
pub fn is_empty(&self) -> bool {
self.files.is_empty()
}
}
macro_rules! single_input {
($($ty:ty),*) => {
$(impl From<$ty> for ToolInput {
fn from(value: $ty) -> Self {
ToolInput { files: vec![FileInput::from(value)] }
}
})*
};
}
single_input!(&str, String, &String, &Path, PathBuf, &PathBuf, &Document, Document, VersionRef);
impl From<FileInput> for ToolInput {
fn from(file: FileInput) -> Self {
ToolInput { files: vec![file] }
}
}
impl<F: Into<FileInput>> From<Vec<F>> for ToolInput {
fn from(files: Vec<F>) -> Self {
ToolInput::many(files)
}
}
impl<F: Into<FileInput>, const N: usize> From<[F; N]> for ToolInput {
fn from(files: [F; N]) -> Self {
ToolInput::many(files)
}
}