lc_schema/messages/
file.rs1use serde::{Deserialize, Serialize};
8
9#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
14pub struct FileContent {
15 pub url: String,
17 pub mime_type: Option<String>,
19 pub name: Option<String>,
21}
22
23impl FileContent {
24 pub fn from_url(url: impl Into<String>) -> Self {
26 Self {
27 url: url.into(),
28 mime_type: None,
29 name: None,
30 }
31 }
32
33 pub fn from_base64(data: impl Into<String>, mime: &str) -> Self {
35 Self {
36 url: format!("data:{};base64,{}", mime, data.into()),
37 mime_type: Some(mime.to_string()),
38 name: None,
39 }
40 }
41
42 pub fn from_url_with_mime(url: impl Into<String>, mime: impl Into<String>) -> Self {
44 Self {
45 url: url.into(),
46 mime_type: Some(mime.into()),
47 name: None,
48 }
49 }
50
51 pub fn with_name(mut self, name: impl Into<String>) -> Self {
53 self.name = Some(name.into());
54 self
55 }
56
57 pub fn is_base64(&self) -> bool {
59 self.url.starts_with("data:")
60 }
61
62 pub fn base64_data(&self) -> Option<&str> {
64 self.url
65 .split_once(',')
66 .filter(|(prefix, _)| prefix.contains("base64"))
67 .map(|(_, data)| data)
68 }
69}
70
71#[cfg(test)]
72mod tests {
73 use super::*;
74
75 #[test]
76 fn test_from_url() {
77 let file = FileContent::from_url("https://example.com/doc.pdf");
78 assert_eq!(file.url, "https://example.com/doc.pdf");
79 assert!(!file.is_base64());
80 assert!(file.mime_type.is_none());
81 }
82
83 #[test]
84 fn test_from_url_with_mime() {
85 let file = FileContent::from_url_with_mime("https://example.com/data.csv", "text/csv");
86 assert_eq!(file.mime_type, Some("text/csv".to_string()));
87 }
88
89 #[test]
90 fn test_from_base64() {
91 let file = FileContent::from_base64("abc123", "application/pdf");
92 assert!(file.is_base64());
93 assert_eq!(file.mime_type, Some("application/pdf".to_string()));
94 assert_eq!(file.base64_data(), Some("abc123"));
95 }
96
97 #[test]
98 fn test_with_name() {
99 let file = FileContent::from_url("https://example.com/doc.pdf").with_name("report.pdf");
100 assert_eq!(file.name, Some("report.pdf".to_string()));
101 }
102}