Skip to main content

stripe_shared/
file.rs

1/// This object represents files hosted on Stripe's servers. You can upload
2/// files with the [create file](https://api.stripe.com#create_file) request
3/// (for example, when uploading dispute evidence). Stripe also
4/// creates files independently (for example, the results of a [Sigma scheduled
5/// query](#scheduled_queries)).
6///
7/// Related guide: [File upload guide](https://docs.stripe.com/file-upload)
8///
9/// For more details see <<https://stripe.com/docs/api/files/object>>.
10#[derive(Clone)]
11#[cfg_attr(not(feature = "redact-generated-debug"), derive(Debug))]
12#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
13pub struct File {
14    /// Time at which the object was created. Measured in seconds since the Unix epoch.
15    pub created: stripe_types::Timestamp,
16    /// The file expires and isn't available at this time in epoch seconds.
17    pub expires_at: Option<stripe_types::Timestamp>,
18    /// The suitable name for saving the file to a filesystem.
19    pub filename: Option<String>,
20    /// Unique identifier for the object.
21    pub id: stripe_shared::FileId,
22    /// A list of [file links](https://api.stripe.com#file_links) that point at this file.
23    pub links: Option<stripe_types::List<stripe_shared::FileLink>>,
24    /// The [purpose](https://docs.stripe.com/file-upload#uploading-a-file) of the uploaded file.
25    pub purpose: stripe_shared::FilePurpose,
26    /// The size of the file object in bytes.
27    pub size: u64,
28    /// A suitable title for the document.
29    pub title: Option<String>,
30    /// The returned file type (for example, `csv`, `pdf`, `jpg`, or `png`).
31    #[cfg_attr(feature = "deserialize", serde(rename = "type"))]
32    pub type_: Option<String>,
33    /// Use your live secret API key to download the file from this URL.
34    pub url: Option<String>,
35}
36#[cfg(feature = "redact-generated-debug")]
37impl std::fmt::Debug for File {
38    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
39        f.debug_struct("File").finish_non_exhaustive()
40    }
41}
42#[doc(hidden)]
43pub struct FileBuilder {
44    created: Option<stripe_types::Timestamp>,
45    expires_at: Option<Option<stripe_types::Timestamp>>,
46    filename: Option<Option<String>>,
47    id: Option<stripe_shared::FileId>,
48    links: Option<Option<stripe_types::List<stripe_shared::FileLink>>>,
49    purpose: Option<stripe_shared::FilePurpose>,
50    size: Option<u64>,
51    title: Option<Option<String>>,
52    type_: Option<Option<String>>,
53    url: Option<Option<String>>,
54}
55
56#[allow(
57    unused_variables,
58    irrefutable_let_patterns,
59    clippy::let_unit_value,
60    clippy::match_single_binding,
61    clippy::single_match
62)]
63const _: () = {
64    use miniserde::de::{Map, Visitor};
65    use miniserde::json::Value;
66    use miniserde::{Deserialize, Result, make_place};
67    use stripe_types::miniserde_helpers::FromValueOpt;
68    use stripe_types::{MapBuilder, ObjectDeser};
69
70    make_place!(Place);
71
72    impl Deserialize for File {
73        fn begin(out: &mut Option<Self>) -> &mut dyn Visitor {
74            Place::new(out)
75        }
76    }
77
78    struct Builder<'a> {
79        out: &'a mut Option<File>,
80        builder: FileBuilder,
81    }
82
83    impl Visitor for Place<File> {
84        fn map(&mut self) -> Result<Box<dyn Map + '_>> {
85            Ok(Box::new(Builder { out: &mut self.out, builder: FileBuilder::deser_default() }))
86        }
87    }
88
89    impl MapBuilder for FileBuilder {
90        type Out = File;
91        fn key(&mut self, k: &str) -> Result<&mut dyn Visitor> {
92            Ok(match k {
93                "created" => Deserialize::begin(&mut self.created),
94                "expires_at" => Deserialize::begin(&mut self.expires_at),
95                "filename" => Deserialize::begin(&mut self.filename),
96                "id" => Deserialize::begin(&mut self.id),
97                "links" => Deserialize::begin(&mut self.links),
98                "purpose" => Deserialize::begin(&mut self.purpose),
99                "size" => Deserialize::begin(&mut self.size),
100                "title" => Deserialize::begin(&mut self.title),
101                "type" => Deserialize::begin(&mut self.type_),
102                "url" => Deserialize::begin(&mut self.url),
103                _ => <dyn Visitor>::ignore(),
104            })
105        }
106
107        fn deser_default() -> Self {
108            Self {
109                created: Deserialize::default(),
110                expires_at: Deserialize::default(),
111                filename: Deserialize::default(),
112                id: Deserialize::default(),
113                links: Deserialize::default(),
114                purpose: Deserialize::default(),
115                size: Deserialize::default(),
116                title: Deserialize::default(),
117                type_: Deserialize::default(),
118                url: Deserialize::default(),
119            }
120        }
121
122        fn take_out(&mut self) -> Option<Self::Out> {
123            let (
124                Some(created),
125                Some(expires_at),
126                Some(filename),
127                Some(id),
128                Some(links),
129                Some(purpose),
130                Some(size),
131                Some(title),
132                Some(type_),
133                Some(url),
134            ) = (
135                self.created,
136                self.expires_at,
137                self.filename.take(),
138                self.id.take(),
139                self.links.take(),
140                self.purpose.take(),
141                self.size,
142                self.title.take(),
143                self.type_.take(),
144                self.url.take(),
145            )
146            else {
147                return None;
148            };
149            Some(Self::Out {
150                created,
151                expires_at,
152                filename,
153                id,
154                links,
155                purpose,
156                size,
157                title,
158                type_,
159                url,
160            })
161        }
162    }
163
164    impl Map for Builder<'_> {
165        fn key(&mut self, k: &str) -> Result<&mut dyn Visitor> {
166            self.builder.key(k)
167        }
168
169        fn finish(&mut self) -> Result<()> {
170            *self.out = self.builder.take_out();
171            Ok(())
172        }
173    }
174
175    impl ObjectDeser for File {
176        type Builder = FileBuilder;
177    }
178
179    impl FromValueOpt for File {
180        fn from_value(v: Value) -> Option<Self> {
181            let Value::Object(obj) = v else {
182                return None;
183            };
184            let mut b = FileBuilder::deser_default();
185            for (k, v) in obj {
186                match k.as_str() {
187                    "created" => b.created = FromValueOpt::from_value(v),
188                    "expires_at" => b.expires_at = FromValueOpt::from_value(v),
189                    "filename" => b.filename = FromValueOpt::from_value(v),
190                    "id" => b.id = FromValueOpt::from_value(v),
191                    "links" => b.links = FromValueOpt::from_value(v),
192                    "purpose" => b.purpose = FromValueOpt::from_value(v),
193                    "size" => b.size = FromValueOpt::from_value(v),
194                    "title" => b.title = FromValueOpt::from_value(v),
195                    "type" => b.type_ = FromValueOpt::from_value(v),
196                    "url" => b.url = FromValueOpt::from_value(v),
197                    _ => {}
198                }
199            }
200            b.take_out()
201        }
202    }
203};
204#[cfg(feature = "serialize")]
205impl serde::Serialize for File {
206    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
207        use serde::ser::SerializeStruct;
208        let mut s = s.serialize_struct("File", 11)?;
209        s.serialize_field("created", &self.created)?;
210        s.serialize_field("expires_at", &self.expires_at)?;
211        s.serialize_field("filename", &self.filename)?;
212        s.serialize_field("id", &self.id)?;
213        s.serialize_field("links", &self.links)?;
214        s.serialize_field("purpose", &self.purpose)?;
215        s.serialize_field("size", &self.size)?;
216        s.serialize_field("title", &self.title)?;
217        s.serialize_field("type", &self.type_)?;
218        s.serialize_field("url", &self.url)?;
219
220        s.serialize_field("object", "file")?;
221        s.end()
222    }
223}
224impl stripe_types::Object for File {
225    type Id = stripe_shared::FileId;
226    fn id(&self) -> &Self::Id {
227        &self.id
228    }
229
230    fn into_id(self) -> Self::Id {
231        self.id
232    }
233}
234stripe_types::def_id!(FileId);
235#[derive(Clone, Eq, PartialEq)]
236#[non_exhaustive]
237pub enum FilePurpose {
238    AccountRequirement,
239    AdditionalVerification,
240    BusinessIcon,
241    BusinessLogo,
242    CustomerSignature,
243    DisputeEvidence,
244    DocumentProviderIdentityDocument,
245    FinanceReportRun,
246    FinancialAccountStatement,
247    IdentityDocument,
248    IdentityDocumentDownloadable,
249    IssuingRegulatoryReporting,
250    PciDocument,
251    PlatformTermsOfService,
252    Selfie,
253    SigmaScheduledQuery,
254    TaxDocumentUserUpload,
255    TerminalAndroidApk,
256    TerminalReaderSplashscreen,
257    TerminalWifiCertificate,
258    TerminalWifiPrivateKey,
259    /// An unrecognized value from Stripe. Should not be used as a request parameter.
260    Unknown(String),
261}
262impl FilePurpose {
263    pub fn as_str(&self) -> &str {
264        use FilePurpose::*;
265        match self {
266            AccountRequirement => "account_requirement",
267            AdditionalVerification => "additional_verification",
268            BusinessIcon => "business_icon",
269            BusinessLogo => "business_logo",
270            CustomerSignature => "customer_signature",
271            DisputeEvidence => "dispute_evidence",
272            DocumentProviderIdentityDocument => "document_provider_identity_document",
273            FinanceReportRun => "finance_report_run",
274            FinancialAccountStatement => "financial_account_statement",
275            IdentityDocument => "identity_document",
276            IdentityDocumentDownloadable => "identity_document_downloadable",
277            IssuingRegulatoryReporting => "issuing_regulatory_reporting",
278            PciDocument => "pci_document",
279            PlatformTermsOfService => "platform_terms_of_service",
280            Selfie => "selfie",
281            SigmaScheduledQuery => "sigma_scheduled_query",
282            TaxDocumentUserUpload => "tax_document_user_upload",
283            TerminalAndroidApk => "terminal_android_apk",
284            TerminalReaderSplashscreen => "terminal_reader_splashscreen",
285            TerminalWifiCertificate => "terminal_wifi_certificate",
286            TerminalWifiPrivateKey => "terminal_wifi_private_key",
287            Unknown(v) => v,
288        }
289    }
290}
291
292impl std::str::FromStr for FilePurpose {
293    type Err = std::convert::Infallible;
294    fn from_str(s: &str) -> Result<Self, Self::Err> {
295        use FilePurpose::*;
296        match s {
297            "account_requirement" => Ok(AccountRequirement),
298            "additional_verification" => Ok(AdditionalVerification),
299            "business_icon" => Ok(BusinessIcon),
300            "business_logo" => Ok(BusinessLogo),
301            "customer_signature" => Ok(CustomerSignature),
302            "dispute_evidence" => Ok(DisputeEvidence),
303            "document_provider_identity_document" => Ok(DocumentProviderIdentityDocument),
304            "finance_report_run" => Ok(FinanceReportRun),
305            "financial_account_statement" => Ok(FinancialAccountStatement),
306            "identity_document" => Ok(IdentityDocument),
307            "identity_document_downloadable" => Ok(IdentityDocumentDownloadable),
308            "issuing_regulatory_reporting" => Ok(IssuingRegulatoryReporting),
309            "pci_document" => Ok(PciDocument),
310            "platform_terms_of_service" => Ok(PlatformTermsOfService),
311            "selfie" => Ok(Selfie),
312            "sigma_scheduled_query" => Ok(SigmaScheduledQuery),
313            "tax_document_user_upload" => Ok(TaxDocumentUserUpload),
314            "terminal_android_apk" => Ok(TerminalAndroidApk),
315            "terminal_reader_splashscreen" => Ok(TerminalReaderSplashscreen),
316            "terminal_wifi_certificate" => Ok(TerminalWifiCertificate),
317            "terminal_wifi_private_key" => Ok(TerminalWifiPrivateKey),
318            v => {
319                tracing::warn!("Unknown value '{}' for enum '{}'", v, "FilePurpose");
320                Ok(Unknown(v.to_owned()))
321            }
322        }
323    }
324}
325impl std::fmt::Display for FilePurpose {
326    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
327        f.write_str(self.as_str())
328    }
329}
330
331#[cfg(not(feature = "redact-generated-debug"))]
332impl std::fmt::Debug for FilePurpose {
333    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
334        f.write_str(self.as_str())
335    }
336}
337#[cfg(feature = "redact-generated-debug")]
338impl std::fmt::Debug for FilePurpose {
339    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
340        f.debug_struct(stringify!(FilePurpose)).finish_non_exhaustive()
341    }
342}
343impl serde::Serialize for FilePurpose {
344    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
345    where
346        S: serde::Serializer,
347    {
348        serializer.serialize_str(self.as_str())
349    }
350}
351impl miniserde::Deserialize for FilePurpose {
352    fn begin(out: &mut Option<Self>) -> &mut dyn miniserde::de::Visitor {
353        crate::Place::new(out)
354    }
355}
356
357impl miniserde::de::Visitor for crate::Place<FilePurpose> {
358    fn string(&mut self, s: &str) -> miniserde::Result<()> {
359        use std::str::FromStr;
360        self.out = Some(FilePurpose::from_str(s).expect("infallible"));
361        Ok(())
362    }
363}
364
365stripe_types::impl_from_val_with_from_str!(FilePurpose);
366#[cfg(feature = "deserialize")]
367impl<'de> serde::Deserialize<'de> for FilePurpose {
368    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
369        use std::str::FromStr;
370        let s: std::borrow::Cow<'de, str> = serde::Deserialize::deserialize(deserializer)?;
371        Ok(Self::from_str(&s).expect("infallible"))
372    }
373}