1use std::fmt;
4use std::future::{Future, IntoFuture};
5use std::path::{Path, PathBuf};
6use std::pin::Pin;
7use std::sync::{Arc, Mutex};
8
9use laravel::http::{Download, UploadedFile};
10use laravel::queue::{BatchId, ChainDispatched};
11use serde::{Deserialize, Serialize};
12
13use crate::config::ExcelConfig;
14use crate::error::ExcelError;
15use crate::events::GlobalListeners;
16use crate::export::{Export, ExportContext};
17use crate::fake::FakeState;
18use crate::import::{Import, ImportContext, SheetRows, SheetWindow};
19use crate::reader::{ReadOptions, ReadSheet};
20use crate::sheets::SheetKey;
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
24pub enum Type {
25 Xlsx,
27 Csv,
29 Tsv,
31 Ods,
33 Xls,
35 Slk,
37 Xml,
39 Gnumeric,
41 Html,
43 Mpdf,
45 Dompdf,
47 Tcpdf,
49}
50
51impl fmt::Display for Type {
52 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53 let name = match self {
54 Self::Xlsx => "Xlsx",
55 Self::Csv | Self::Tsv => "Csv",
56 Self::Ods => "Ods",
57 Self::Xls => "Xls",
58 Self::Slk => "Slk",
59 Self::Xml => "Xml",
60 Self::Gnumeric => "Gnumeric",
61 Self::Html => "Html",
62 Self::Mpdf => "Mpdf",
63 Self::Dompdf => "Dompdf",
64 Self::Tcpdf => "Tcpdf",
65 };
66 f.write_str(name)
67 }
68}
69
70fn extension(path: &str) -> Option<String> {
71 Path::new(path)
72 .extension()
73 .map(|extension| extension.to_string_lossy().to_lowercase())
74 .filter(|extension| !extension.trim().is_empty())
75}
76
77pub(crate) fn detect(path: &str, explicit: Option<Type>, config: &ExcelConfig) -> Result<Option<Type>, ExcelError> {
79 if explicit.is_some() {
80 return Ok(explicit);
81 }
82 let extension = extension(path).ok_or(ExcelError::NoTypeDetected)?;
83 Ok(config.extension_detector.get(&extension).copied())
84}
85
86pub(crate) fn detect_strict(path: &str, explicit: Option<Type>, config: &ExcelConfig) -> Result<Type, ExcelError> {
88 detect(path, explicit, config)?.ok_or(ExcelError::NoTypeDetected)
89}
90
91fn identify(bytes: &[u8]) -> Type {
93 if bytes.starts_with(b"PK") {
94 let head = &bytes[..bytes.len().min(200)];
95 if head.windows(8).any(|window| window == b"mimetype")
96 && head.windows(11).any(|window| window == b"opendocumen")
97 {
98 return Type::Ods;
99 }
100 return Type::Xlsx;
101 }
102 if bytes.starts_with(&[0xD0, 0xCF, 0x11, 0xE0]) {
103 return Type::Xls;
104 }
105 if bytes.starts_with(&[0x1F, 0x8B]) {
106 return Type::Gnumeric;
107 }
108 if bytes.starts_with(b"ID;") {
109 return Type::Slk;
110 }
111 let head = String::from_utf8_lossy(&bytes[..bytes.len().min(2048)]).to_ascii_lowercase();
112 if head.contains("urn:schemas-microsoft-com:office:spreadsheet") {
113 return Type::Xml;
114 }
115 if head.trim_start().starts_with("<!doctype html") || head.contains("<html") || head.contains("<table") {
116 return Type::Html;
117 }
118 Type::Csv
119}
120
121#[derive(Clone, Default)]
123pub struct ExcelState {
124 pub(crate) listeners: GlobalListeners,
125 pub(crate) fake: Arc<Mutex<Option<Arc<FakeState>>>>,
126}
127
128pub(crate) async fn state() -> ExcelState {
129 match laravel::container::resolve::<ExcelState>().await {
130 Ok(state) => (*state).clone(),
131 Err(_) => ExcelState::default(),
132 }
133}
134
135pub(crate) async fn global_listeners() -> GlobalListeners {
136 state().await.listeners
137}
138
139pub(crate) async fn fake() -> Option<Arc<FakeState>> {
140 state()
141 .await
142 .fake
143 .lock()
144 .unwrap_or_else(std::sync::PoisonError::into_inner)
145 .clone()
146}
147
148#[derive(Debug, Clone)]
150pub enum ImportFile {
151 Path(String),
154 Uploaded {
156 path: PathBuf,
158 name: String,
160 },
161}
162
163impl ImportFile {
164 pub fn name(&self) -> &str {
166 match self {
167 Self::Path(path) => path,
168 Self::Uploaded { name, .. } => name,
169 }
170 }
171
172 pub(crate) async fn read(&self, disk: Option<&str>) -> laravel::Result<Vec<u8>> {
173 match self {
174 Self::Uploaded { path, .. } => Ok(std::fs::read(path)?),
175 Self::Path(path) => {
176 if disk.is_none() {
177 let local = Path::new(path);
178 let absolute = if local.is_absolute() {
179 local.to_path_buf()
180 } else {
181 laravel::config().app.base_path.join(local)
182 };
183 if absolute.is_file() {
184 let on_default_disk = match laravel::storage::default_disk() {
185 Ok(default) if !local.is_absolute() => default.exists(path).await.unwrap_or(false),
186 _ => false,
187 };
188 if !on_default_disk {
189 return Ok(std::fs::read(absolute)?);
190 }
191 }
192 }
193 let storage = match disk {
194 Some(name) => laravel::storage::disk(name)?,
195 None => laravel::storage::default_disk()?,
196 };
197 if !storage.exists(path).await? {
198 let mut log = format!("[{path}]");
199 if let Some(disk) = disk {
200 log.push_str(&format!(" ({disk})"));
201 }
202 return Err(ExcelError::UnreadableFile(format!(
203 "File {log} does not exist and can therefore not be imported."
204 ))
205 .into());
206 }
207 Ok(storage.get_with_limit(path, u64::MAX).await?.to_vec())
208 }
209 }
210 }
211}
212
213impl From<&str> for ImportFile {
214 fn from(path: &str) -> Self {
215 Self::Path(path.to_owned())
216 }
217}
218
219impl From<String> for ImportFile {
220 fn from(path: String) -> Self {
221 Self::Path(path)
222 }
223}
224
225impl From<&String> for ImportFile {
226 fn from(path: &String) -> Self {
227 Self::Path(path.clone())
228 }
229}
230
231impl From<&UploadedFile> for ImportFile {
232 fn from(file: &UploadedFile) -> Self {
233 Self::Uploaded {
234 path: file.path().to_path_buf(),
235 name: file.client_name().to_owned(),
236 }
237 }
238}
239
240#[derive(Debug)]
242pub enum Queued {
243 Chain(ChainDispatched),
245 Batch(BatchId),
247 Jobs(usize),
249 Faked,
251}
252
253type BoxedFuture<'a, T> = Pin<Box<dyn Future<Output = laravel::Result<T>> + Send + 'a>>;
254
255pub struct Excel;
269
270impl Excel {
271 pub fn download<'a, E: AsDynExport + ?Sized>(
274 export: &'a E,
275 file_name: impl Into<String>,
276 ) -> PendingDownload<'a, E> {
277 PendingDownload {
278 export,
279 file_name: file_name.into(),
280 writer_type: None,
281 headers: Vec::new(),
282 }
283 }
284
285 pub fn store<'a, E: AsDynExport + ?Sized>(export: &'a E, file_path: impl Into<String>) -> PendingStore<'a, E> {
288 PendingStore {
289 export,
290 file_path: file_path.into(),
291 disk: None,
292 writer_type: None,
293 }
294 }
295
296 pub fn queue<'a, E: AsDynExport + ?Sized>(export: &'a E, file_path: impl Into<String>) -> PendingQueue<'a, E> {
299 PendingQueue {
300 export,
301 file_path: file_path.into(),
302 disk: None,
303 writer_type: None,
304 }
305 }
306
307 pub async fn raw<E: AsDynExport + ?Sized>(export: &E, writer_type: Type) -> laravel::Result<Vec<u8>> {
309 let export = export.__as_dyn();
310 if let Some(fake) = fake().await {
311 fake.record_raw(export);
312 return Ok(b"RAW-CONTENTS".to_vec());
313 }
314 let context = ExportContext::current().await;
315 let mut spreadsheet = crate::export::build(export, &context).await?;
316 write_spreadsheet(export, &mut spreadsheet, writer_type, None, &context)
317 }
318
319 pub fn import<'a, I: AsDynImport + ?Sized>(import: &'a I, file: impl Into<ImportFile>) -> PendingImport<'a, I> {
323 PendingImport {
324 import,
325 file: file.into(),
326 disk: None,
327 reader_type: None,
328 }
329 }
330
331 pub fn queue_import<'a, I: AsDynImport + ?Sized>(
333 import: &'a I,
334 file: impl Into<ImportFile>,
335 ) -> PendingQueueImport<'a, I> {
336 PendingQueueImport(PendingImport {
337 import,
338 file: file.into(),
339 disk: None,
340 reader_type: None,
341 })
342 }
343
344 pub fn to_array<'a, I: AsDynImport + ?Sized>(import: &'a I, file: impl Into<ImportFile>) -> PendingRows<'a, I> {
346 PendingRows(PendingImport {
347 import,
348 file: file.into(),
349 disk: None,
350 reader_type: None,
351 })
352 }
353
354 pub fn to_collection<'a, I: AsDynImport + ?Sized>(
357 import: &'a I,
358 file: impl Into<ImportFile>,
359 ) -> PendingRows<'a, I> {
360 Self::to_array(import, file)
361 }
362}
363
364#[doc(hidden)]
366pub trait AsDynExport: Sync {
367 fn __as_dyn(&self) -> &dyn Export;
368}
369
370impl<E: Export> AsDynExport for E {
371 fn __as_dyn(&self) -> &dyn Export {
372 self
373 }
374}
375
376impl AsDynExport for dyn Export {
377 fn __as_dyn(&self) -> &dyn Export {
378 self
379 }
380}
381
382#[doc(hidden)]
383pub trait AsDynImport: Sync {
384 fn __as_dyn(&self) -> &dyn Import;
385}
386
387impl<I: Import> AsDynImport for I {
388 fn __as_dyn(&self) -> &dyn Import {
389 self
390 }
391}
392
393impl AsDynImport for dyn Import {
394 fn __as_dyn(&self) -> &dyn Import {
395 self
396 }
397}
398
399pub(crate) fn write_spreadsheet(
401 export: &dyn Export,
402 spreadsheet: &mut crate::spreadsheet::Spreadsheet,
403 writer_type: Type,
404 file_name: Option<&str>,
405 context: &ExportContext,
406) -> laravel::Result<Vec<u8>> {
407 crate::export::before_writing(export, spreadsheet, context)?;
408 let concerns = export.__concerns();
409 let mut csv = match concerns.csv_settings {
410 Some(settings) => settings.csv_settings(),
411 None => context.config.exports.csv.clone(),
412 };
413 let tsv = writer_type == Type::Tsv || file_name.is_some_and(|name| extension(name).as_deref() == Some("tsv"));
414 if tsv && concerns.csv_settings.is_none() {
415 csv.delimiter = "\t".to_owned();
416 }
417 let pre_calculate = concerns.pre_calculate_formulas || context.config.exports.pre_calculate_formulas;
418 Ok(crate::writer::write(spreadsheet, writer_type, &csv, pre_calculate)?)
419}
420
421pub(crate) async fn export_bytes(export: &dyn Export, file_name: &str, writer_type: Type) -> laravel::Result<Vec<u8>> {
423 let context = ExportContext::current().await;
424 let mut spreadsheet = crate::export::build(export, &context).await?;
425 write_spreadsheet(export, &mut spreadsheet, writer_type, Some(file_name), &context)
426}
427
428#[must_use = "await the download to build the response"]
430pub struct PendingDownload<'a, E: ?Sized> {
431 export: &'a E,
432 file_name: String,
433 writer_type: Option<Type>,
434 headers: Vec<(String, String)>,
435}
436
437impl<E: ?Sized> PendingDownload<'_, E> {
438 pub fn writer_type(mut self, writer_type: Type) -> Self {
440 self.writer_type = Some(writer_type);
441 self
442 }
443
444 pub fn headers<K: Into<String>, V: Into<String>>(mut self, headers: impl IntoIterator<Item = (K, V)>) -> Self {
446 self.headers
447 .extend(headers.into_iter().map(|(name, value)| (name.into(), value.into())));
448 self
449 }
450}
451
452impl<'a, E: AsDynExport + ?Sized> IntoFuture for PendingDownload<'a, E> {
453 type Output = laravel::Result<Download>;
454 type IntoFuture = BoxedFuture<'a, Download>;
455
456 fn into_future(self) -> Self::IntoFuture {
457 Box::pin(async move {
458 let export = self.export.__as_dyn();
459 if let Some(fake) = fake().await {
460 fake.record_download(&self.file_name, export);
461 return Ok(Download::new(self.file_name, Vec::<u8>::new()));
462 }
463 let config = crate::config::current();
464 let writer_type = detect_strict(&self.file_name, self.writer_type, &config)?;
465 let bytes = export_bytes(export, &self.file_name, writer_type).await?;
466 let mut download = Download::new(self.file_name, bytes);
467 for (name, value) in self.headers {
468 download = download.with_header(name, value);
469 }
470 Ok(download)
471 })
472 }
473}
474
475#[must_use = "await the store to write the file"]
477pub struct PendingStore<'a, E: ?Sized> {
478 export: &'a E,
479 file_path: String,
480 disk: Option<String>,
481 writer_type: Option<Type>,
482}
483
484impl<E: ?Sized> PendingStore<'_, E> {
485 pub fn disk(mut self, disk: impl Into<String>) -> Self {
487 self.disk = Some(disk.into());
488 self
489 }
490
491 pub fn writer_type(mut self, writer_type: Type) -> Self {
493 self.writer_type = Some(writer_type);
494 self
495 }
496}
497
498impl<'a, E: AsDynExport + ?Sized> IntoFuture for PendingStore<'a, E> {
499 type Output = laravel::Result<bool>;
500 type IntoFuture = BoxedFuture<'a, bool>;
501
502 fn into_future(self) -> Self::IntoFuture {
503 Box::pin(async move {
504 let export = self.export.__as_dyn();
505 if export.__concerns().should_queue.is_some() {
506 crate::queue::queue_export(export, &self.file_path, self.disk.as_deref(), self.writer_type).await?;
507 return Ok(true);
508 }
509 if let Some(fake) = fake().await {
510 fake.record_store(self.disk.as_deref(), &self.file_path, export);
511 return Ok(true);
512 }
513 let config = crate::config::current();
514 let writer_type = detect_strict(&self.file_path, self.writer_type, &config)?;
515 let bytes = export_bytes(export, &self.file_path, writer_type).await?;
516 let disk = match &self.disk {
517 Some(name) => laravel::storage::disk(name)?,
518 None => laravel::storage::default_disk()?,
519 };
520 disk.put(&self.file_path, bytes).await?;
521 Ok(true)
522 })
523 }
524}
525
526#[must_use = "await the queue to dispatch the jobs"]
528pub struct PendingQueue<'a, E: ?Sized> {
529 export: &'a E,
530 file_path: String,
531 disk: Option<String>,
532 writer_type: Option<Type>,
533}
534
535impl<E: ?Sized> PendingQueue<'_, E> {
536 pub fn disk(mut self, disk: impl Into<String>) -> Self {
538 self.disk = Some(disk.into());
539 self
540 }
541
542 pub fn writer_type(mut self, writer_type: Type) -> Self {
544 self.writer_type = Some(writer_type);
545 self
546 }
547}
548
549impl<'a, E: AsDynExport + ?Sized> IntoFuture for PendingQueue<'a, E> {
550 type Output = laravel::Result<Queued>;
551 type IntoFuture = BoxedFuture<'a, Queued>;
552
553 fn into_future(self) -> Self::IntoFuture {
554 Box::pin(async move {
555 crate::queue::queue_export(
556 self.export.__as_dyn(),
557 &self.file_path,
558 self.disk.as_deref(),
559 self.writer_type,
560 )
561 .await
562 })
563 }
564}
565
566#[must_use = "await the import to read the file"]
568pub struct PendingImport<'a, I: ?Sized> {
569 import: &'a I,
570 file: ImportFile,
571 disk: Option<String>,
572 reader_type: Option<Type>,
573}
574
575impl<I: ?Sized> PendingImport<'_, I> {
576 pub fn disk(mut self, disk: impl Into<String>) -> Self {
578 self.disk = Some(disk.into());
579 self
580 }
581
582 pub fn reader_type(mut self, reader_type: Type) -> Self {
584 self.reader_type = Some(reader_type);
585 self
586 }
587}
588
589impl<'a, I: AsDynImport + ?Sized> IntoFuture for PendingImport<'a, I> {
590 type Output = laravel::Result<Option<Queued>>;
591 type IntoFuture = BoxedFuture<'a, Option<Queued>>;
592
593 fn into_future(self) -> Self::IntoFuture {
594 Box::pin(async move {
595 let import = self.import.__as_dyn();
596 if let Some(fake) = fake().await {
597 if import.__concerns().should_queue.is_some() {
598 fake.record_queued_import(self.disk.as_deref(), self.file.name(), import);
599 return Ok(Some(Queued::Faked));
600 }
601 fake.record_import(self.disk.as_deref(), self.file.name(), import);
602 return Ok(None);
603 }
604 read(import, &self.file, self.disk.as_deref(), self.reader_type).await
605 })
606 }
607}
608
609#[must_use = "await the import to dispatch its jobs"]
611pub struct PendingQueueImport<'a, I: ?Sized>(PendingImport<'a, I>);
612
613impl<I: ?Sized> PendingQueueImport<'_, I> {
614 pub fn disk(self, disk: impl Into<String>) -> Self {
616 Self(self.0.disk(disk))
617 }
618
619 pub fn reader_type(self, reader_type: Type) -> Self {
621 Self(self.0.reader_type(reader_type))
622 }
623}
624
625impl<'a, I: AsDynImport + ?Sized> IntoFuture for PendingQueueImport<'a, I> {
626 type Output = laravel::Result<Queued>;
627 type IntoFuture = BoxedFuture<'a, Queued>;
628
629 fn into_future(self) -> Self::IntoFuture {
630 Box::pin(async move {
631 if self.0.import.__as_dyn().__concerns().should_queue.is_none() {
632 return Err(ExcelError::NotQueueable.into());
633 }
634 self.0.await?.ok_or_else(|| ExcelError::NotQueueable.into())
635 })
636 }
637}
638
639#[must_use = "await the rows to read the file"]
641pub struct PendingRows<'a, I: ?Sized>(PendingImport<'a, I>);
642
643impl<I: ?Sized> PendingRows<'_, I> {
644 pub fn disk(self, disk: impl Into<String>) -> Self {
646 Self(self.0.disk(disk))
647 }
648
649 pub fn reader_type(self, reader_type: Type) -> Self {
651 Self(self.0.reader_type(reader_type))
652 }
653}
654
655impl<'a, I: AsDynImport + ?Sized> IntoFuture for PendingRows<'a, I> {
656 type Output = laravel::Result<SheetRows>;
657 type IntoFuture = BoxedFuture<'a, SheetRows>;
658
659 fn into_future(self) -> Self::IntoFuture {
660 Box::pin(async move {
661 let pending = self.0;
662 let import = pending.import.__as_dyn();
663 if let Some(fake) = fake().await {
664 fake.record_import(pending.disk.as_deref(), pending.file.name(), import);
665 return Ok(SheetRows::new());
666 }
667 to_rows(import, &pending.file, pending.disk.as_deref(), pending.reader_type).await
668 })
669 }
670}
671
672pub(crate) async fn load(
674 import: &dyn Import,
675 bytes: &[u8],
676 file_name: &str,
677 reader_type: Option<Type>,
678 config: &ExcelConfig,
679) -> laravel::Result<(Type, Vec<ReadSheet>)> {
680 let kind = match detect(file_name, reader_type, config)? {
681 Some(kind) => kind,
682 None => identify(bytes),
683 };
684 let concerns = import.__concerns();
685 let csv = match concerns.csv_settings {
686 Some(settings) => settings.csv_import_settings(),
687 None => config.imports.csv.clone(),
688 };
689 let options = ReadOptions {
690 csv,
691 ignore_empty: config.imports.ignore_empty,
692 binder: concerns.binder(config),
693 tsv: extension(file_name).as_deref() == Some("tsv"),
694 style_information: crate::import::requires_style_information(import),
695 };
696 let mut sheets = crate::reader::read(bytes, kind, &options)?;
697 if let Some(filter) = concerns.read_filter {
698 for sheet in &mut sheets {
699 sheet.filter(filter);
700 }
701 }
702 Ok((kind, sheets))
703}
704
705async fn read(
707 import: &dyn Import,
708 file: &ImportFile,
709 disk: Option<&str>,
710 reader_type: Option<Type>,
711) -> laravel::Result<Option<Queued>> {
712 let concerns = import.__concerns();
713 let queued = concerns.should_queue.is_some();
714 let chunked = concerns.chunk_reading.is_some();
715 drop(concerns);
716 if queued && !chunked {
717 return Err(ExcelError::QueueWithoutChunkReading.into());
718 }
719 let context = ImportContext::current().await;
720 let bytes = file.read(disk).await?;
721 if chunked {
722 return crate::queue::read_in_chunks(import, bytes, file.name(), reader_type, &context).await;
723 }
724
725 let result: laravel::Result<()> = async {
726 let (_, mut sheets) = load(import, &bytes, file.name(), reader_type, &context.config).await?;
727 let owned = match import.__concerns().multiple_sheets {
728 Some(multiple) => multiple.sheets().imports(),
729 None => Vec::new(),
730 };
731 let pairs: Vec<(SheetKey, usize, &dyn Import)> = crate::import::sheet_imports(import, &sheets, &owned)?
732 .into_iter()
733 .collect();
734 let total_rows = crate::import::total_rows(&sheets);
735 crate::import::before_import(import, &total_rows, &context.listeners)?;
736 crate::import::transaction(&context.config, async || {
737 for (_, index, sheet_import) in &pairs {
738 let start_row = sheet_import.__concerns().start_row_number();
739 let window = SheetWindow {
740 start_row,
741 end_row: None,
742 chunk_offset: None,
743 };
744 crate::import::import_sheet(*sheet_import, &mut sheets[*index], window, &context).await?;
745 }
746 Ok(())
747 })
748 .await?;
749 crate::import::after_import(import, &total_rows, &context.listeners)
750 }
751 .await;
752 if let Err(error) = &result {
753 crate::import::import_failed(import, error, &context.listeners);
754 }
755 result.map(|()| None)
756}
757
758async fn to_rows(
760 import: &dyn Import,
761 file: &ImportFile,
762 disk: Option<&str>,
763 reader_type: Option<Type>,
764) -> laravel::Result<SheetRows> {
765 let context = ImportContext::current().await;
766 let bytes = file.read(disk).await?;
767 let (_, sheets) = load(import, &bytes, file.name(), reader_type, &context.config).await?;
768 let owned = match import.__concerns().multiple_sheets {
769 Some(multiple) => multiple.sheets().imports(),
770 None => Vec::new(),
771 };
772 let pairs = crate::import::sheet_imports(import, &sheets, &owned)?;
773 let total_rows = crate::import::total_rows(&sheets);
774 crate::import::before_import(import, &total_rows, &context.listeners)?;
775 let mut result = SheetRows::new();
776 for (key, index, sheet_import) in pairs {
777 let start_row = sheet_import.__concerns().start_row_number();
778 let middleware = context.config.imports.cell_middleware.clone();
779 let sheet = crate::import::SheetImport {
780 sheet: &sheets[index],
781 start_row,
782 end_row: None,
783 chunk_offset: None,
784 middleware: &middleware,
785 listeners: &context.listeners,
786 ignore_empty: context.config.imports.ignore_empty,
787 };
788 let rows = crate::import::to_rows(&sheet, sheet_import).await?;
789 result.insert(key, rows);
790 }
791 crate::import::after_import(import, &total_rows, &context.listeners)?;
792 Ok(result)
793}
794
795pub trait Exportable: Export + Sized {
802 fn file_name(&self) -> Option<String> {
804 None
805 }
806
807 fn writer_type(&self) -> Option<Type> {
809 None
810 }
811
812 fn headers(&self) -> Vec<(String, String)> {
814 Vec::new()
815 }
816
817 fn file_path(&self) -> Option<String> {
819 None
820 }
821
822 fn disk(&self) -> Option<String> {
824 None
825 }
826
827 fn download(&self, file_name: Option<&str>) -> impl Future<Output = laravel::Result<Download>> + Send {
829 async move {
830 let file_name = file_name
831 .map(str::to_owned)
832 .or_else(|| self.file_name())
833 .ok_or(ExcelError::NoFilenameGiven)?;
834 let mut pending = Excel::download(self, file_name).headers(self.headers());
835 if let Some(writer_type) = self.writer_type() {
836 pending = pending.writer_type(writer_type);
837 }
838 pending.await
839 }
840 }
841
842 fn store(&self, file_path: Option<&str>) -> impl Future<Output = laravel::Result<bool>> + Send {
844 async move {
845 let file_path = file_path
846 .map(str::to_owned)
847 .or_else(|| self.file_path())
848 .ok_or(ExcelError::NoExportFilePathGiven)?;
849 let mut pending = Excel::store(self, file_path);
850 if let Some(disk) = self.disk() {
851 pending = pending.disk(disk);
852 }
853 if let Some(writer_type) = self.writer_type() {
854 pending = pending.writer_type(writer_type);
855 }
856 pending.await
857 }
858 }
859
860 fn queue(&self, file_path: Option<&str>) -> impl Future<Output = laravel::Result<Queued>> + Send {
862 async move {
863 let file_path = file_path
864 .map(str::to_owned)
865 .or_else(|| self.file_path())
866 .ok_or(ExcelError::NoExportFilePathGiven)?;
867 let mut pending = Excel::queue(self, file_path);
868 if let Some(disk) = self.disk() {
869 pending = pending.disk(disk);
870 }
871 if let Some(writer_type) = self.writer_type() {
872 pending = pending.writer_type(writer_type);
873 }
874 pending.await
875 }
876 }
877
878 fn raw(&self, writer_type: Option<Type>) -> impl Future<Output = laravel::Result<Vec<u8>>> + Send {
880 async move {
881 let writer_type = writer_type
882 .or_else(|| self.writer_type())
883 .ok_or(ExcelError::NoTypeDetected)?;
884 Excel::raw(self, writer_type).await
885 }
886 }
887}
888
889pub trait Importable: Import + Sized {
892 fn file_path(&self) -> Option<String> {
894 None
895 }
896
897 fn disk(&self) -> Option<String> {
899 None
900 }
901
902 fn reader_type(&self) -> Option<Type> {
904 None
905 }
906
907 fn import(&self, file: Option<ImportFile>) -> impl Future<Output = laravel::Result<Option<Queued>>> + Send {
909 async move {
910 let file = file
911 .or_else(|| self.file_path().map(ImportFile::Path))
912 .ok_or(ExcelError::NoImportFilePathGiven)?;
913 let mut pending = Excel::import(self, file);
914 if let Some(disk) = self.disk() {
915 pending = pending.disk(disk);
916 }
917 if let Some(reader_type) = self.reader_type() {
918 pending = pending.reader_type(reader_type);
919 }
920 pending.await
921 }
922 }
923
924 fn to_array(&self, file: Option<ImportFile>) -> impl Future<Output = laravel::Result<SheetRows>> + Send {
926 async move {
927 let file = file
928 .or_else(|| self.file_path().map(ImportFile::Path))
929 .ok_or(ExcelError::NoImportFilePathGiven)?;
930 let mut pending = Excel::to_array(self, file);
931 if let Some(disk) = self.disk() {
932 pending = pending.disk(disk);
933 }
934 if let Some(reader_type) = self.reader_type() {
935 pending = pending.reader_type(reader_type);
936 }
937 pending.await
938 }
939 }
940
941 fn to_collection(&self, file: Option<ImportFile>) -> impl Future<Output = laravel::Result<SheetRows>> + Send {
943 self.to_array(file)
944 }
945
946 fn queue(&self, file: Option<ImportFile>) -> impl Future<Output = laravel::Result<Queued>> + Send {
948 async move {
949 let file = file
950 .or_else(|| self.file_path().map(ImportFile::Path))
951 .ok_or(ExcelError::NoImportFilePathGiven)?;
952 let mut pending = Excel::queue_import(self, file);
953 if let Some(disk) = self.disk() {
954 pending = pending.disk(disk);
955 }
956 if let Some(reader_type) = self.reader_type() {
957 pending = pending.reader_type(reader_type);
958 }
959 pending.await
960 }
961 }
962}