Skip to main content

redmine_api/api/
attachments.rs

1//! Attachments Rest API Endpoint definitions
2//!
3//! [Redmine Documentation](https://www.redmine.org/projects/redmine/wiki/Rest_Attachments)
4//!
5//! - [x] specific attachment endpoint
6//! - [x] update attachment endpoint
7//! - [x] delete attachment endpoint
8
9use derive_builder::Builder;
10use reqwest::Method;
11use std::borrow::Cow;
12
13use crate::api::users::UserEssentials;
14use crate::api::{Endpoint, NoPagination, ReturnsJsonResponse};
15
16/// a type for attachment to use as an API return type
17///
18/// alternatively you can use your own type limited to the fields you need
19#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
20pub struct Attachment {
21    /// numeric id
22    pub id: u64,
23    /// filename as specified on upload
24    pub filename: String,
25    /// file size
26    pub filesize: u64,
27    /// content MIME type
28    pub content_type: Option<String>,
29    /// description
30    #[serde(default)]
31    pub description: Option<String>,
32    /// url where the content of this attachment can be downloaded
33    pub content_url: String,
34    /// uploader
35    pub author: UserEssentials,
36    /// The time when this file was uploaded
37    #[serde(
38        serialize_with = "crate::api::serialize_rfc3339",
39        deserialize_with = "crate::api::deserialize_rfc3339"
40    )]
41    pub created_on: time::OffsetDateTime,
42    /// the URL for the thumbnail for this attachment
43    #[serde(default, skip_serializing_if = "Option::is_none")]
44    pub thumbnail_url: Option<String>,
45    /// A string containing a hash of the file content (e.g., SHA256 or MD5).
46    #[serde(default, skip_serializing_if = "Option::is_none")]
47    pub digest: Option<String>,
48    /// An integer representing the download count.
49    #[serde(default, skip_serializing_if = "Option::is_none")]
50    pub downloads: Option<u64>,
51}
52
53/// The endpoint for a specific Redmine attachment
54#[derive(Debug, Clone, Builder)]
55#[builder(setter(strip_option))]
56pub struct GetAttachment {
57    /// id of the attachment to retrieve
58    id: u64,
59}
60
61impl ReturnsJsonResponse for GetAttachment {}
62impl NoPagination for GetAttachment {}
63
64impl GetAttachment {
65    /// Create a builder for the endpoint.
66    #[must_use]
67    pub fn builder() -> GetAttachmentBuilder {
68        GetAttachmentBuilder::default()
69    }
70}
71
72impl Endpoint for GetAttachment {
73    fn method(&self) -> Method {
74        Method::GET
75    }
76
77    fn endpoint(&self) -> Cow<'static, str> {
78        format!("attachments/{}.json", self.id).into()
79    }
80}
81
82/// The endpoint to update a Redmine attachment
83#[derive(Debug, Clone, Builder)]
84#[builder(setter(strip_option))]
85pub struct UpdateAttachment {
86    /// id of the attachment to update
87    id: u64,
88    /// the attachment update data
89    attachment: AttachmentUpdate,
90}
91
92impl UpdateAttachment {
93    /// Create a builder for the endpoint.
94    #[must_use]
95    pub fn builder() -> UpdateAttachmentBuilder {
96        UpdateAttachmentBuilder::default()
97    }
98}
99
100impl ReturnsJsonResponse for UpdateAttachment {}
101impl NoPagination for UpdateAttachment {}
102
103impl Endpoint for UpdateAttachment {
104    fn method(&self) -> Method {
105        Method::PUT
106    }
107
108    fn endpoint(&self) -> Cow<'static, str> {
109        format!("attachments/{}.json", self.id).into()
110    }
111
112    fn body(&self) -> Result<Option<(&'static str, Vec<u8>)>, crate::Error> {
113        Ok(Some((
114            "application/json",
115            serde_json::to_vec(&AttachmentWrapper {
116                attachment: self.attachment.clone(),
117            })?,
118        )))
119    }
120}
121
122/// The attachment update data
123#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, Default)]
124pub struct AttachmentUpdate {
125    /// new filename
126    #[serde(default, skip_serializing_if = "Option::is_none")]
127    pub filename: Option<String>,
128    /// new description
129    #[serde(default, skip_serializing_if = "Option::is_none")]
130    pub description: Option<String>,
131}
132
133/// The endpoint to delete a Redmine attachment
134#[derive(Debug, Clone, Builder)]
135#[builder(setter(strip_option))]
136pub struct DeleteAttachment {
137    /// id of the attachment to delete
138    id: u64,
139}
140
141impl DeleteAttachment {
142    /// Create a builder for the endpoint.
143    #[must_use]
144    pub fn builder() -> DeleteAttachmentBuilder {
145        DeleteAttachmentBuilder::default()
146    }
147}
148
149impl Endpoint for DeleteAttachment {
150    fn method(&self) -> Method {
151        Method::DELETE
152    }
153
154    fn endpoint(&self) -> Cow<'static, str> {
155        format!("attachments/{}.json", self.id).into()
156    }
157}
158
159/// helper struct for outer layers with a attachment field holding the inner data
160#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
161pub struct AttachmentWrapper<T> {
162    /// to parse JSON with attachment key
163    pub attachment: T,
164}
165
166#[cfg(test)]
167mod test {
168    use super::*;
169    use pretty_assertions::assert_eq;
170    use std::error::Error;
171    use tracing_test::traced_test;
172
173    #[traced_test]
174    #[test]
175    fn test_get_attachment() -> Result<(), Box<dyn Error>> {
176        use crate::api::issues::{
177            CreateIssue, GetIssue, Issue, IssueWrapper, UploadedAttachment, test::ISSUES_LOCK,
178        };
179        use crate::api::test_helpers::with_project;
180        use crate::api::uploads::{FileUploadToken, UploadFile, UploadWrapper};
181
182        let _w_issues = ISSUES_LOCK.blocking_write();
183        with_project("test_get_attachment", |redmine, project_id, _| {
184            let upload_endpoint = UploadFile::builder().file("README.md").build()?;
185            let UploadWrapper {
186                upload: FileUploadToken { id: _, token },
187            } = redmine
188                .json_response_body::<_, UploadWrapper<FileUploadToken>>(&upload_endpoint)?;
189            let create_issue_endpoint = CreateIssue::builder()
190                .project_id(project_id)
191                .subject("Attachment Test Issue")
192                .uploads(vec![UploadedAttachment {
193                    token: token.into(),
194                    filename: "README.md".into(),
195                    description: Some("Uploaded as part of unit test for redmine-api".into()),
196                    content_type: "application/octet-stream".into(),
197                }])
198                .build()?;
199            let IssueWrapper {
200                issue: created_issue,
201            } = redmine.json_response_body::<_, IssueWrapper<Issue>>(&create_issue_endpoint)?;
202
203            let get_issue_endpoint = GetIssue::builder()
204                .id(created_issue.id)
205                .include(vec![crate::api::issues::IssueInclude::Attachments])
206                .build()?;
207            let IssueWrapper { issue } =
208                redmine.json_response_body::<_, IssueWrapper<Issue>>(&get_issue_endpoint)?;
209            let attachment_id = issue.attachments.unwrap().first().unwrap().id;
210
211            let endpoint = GetAttachment::builder().id(attachment_id).build()?;
212            redmine.json_response_body::<_, AttachmentWrapper<Attachment>>(&endpoint)?;
213            Ok(())
214        })
215    }
216
217    /// this tests if any of the results contain a field we are not deserializing
218    ///
219    /// this will only catch fields we missed if they are part of the response but
220    /// it is better than nothing
221    #[traced_test]
222    #[test]
223    fn test_completeness_attachment_type() -> Result<(), Box<dyn Error>> {
224        dotenvy::dotenv()?;
225        let redmine = crate::api::Redmine::from_env(
226            reqwest::blocking::Client::builder()
227                .tls_backend_rustls()
228                .build()?,
229        )?;
230        let endpoint = GetAttachment::builder().id(38468).build()?;
231        let AttachmentWrapper { attachment: value } =
232            redmine.json_response_body::<_, AttachmentWrapper<serde_json::Value>>(&endpoint)?;
233        let o: Attachment = serde_json::from_value(value.clone())?;
234        let reserialized = serde_json::to_value(o)?;
235        assert_eq!(value, reserialized);
236        Ok(())
237    }
238
239    #[traced_test]
240    #[test]
241    fn test_update_delete_attachment() -> Result<(), Box<dyn Error>> {
242        use crate::api::issues::{
243            CreateIssue, GetIssue, Issue, IssueWrapper, UploadedAttachment, test::ISSUES_LOCK,
244        };
245        use crate::api::test_helpers::with_project;
246        use crate::api::uploads::{FileUploadToken, UploadFile, UploadWrapper};
247
248        let _w_issues = ISSUES_LOCK.blocking_write();
249        with_project("test_update_delete_attachment", |redmine, project_id, _| {
250            let upload_endpoint = UploadFile::builder().file("README.md").build()?;
251            let UploadWrapper {
252                upload: FileUploadToken { id: _, token },
253            } = redmine
254                .json_response_body::<_, UploadWrapper<FileUploadToken>>(&upload_endpoint)?;
255            let create_issue_endpoint = CreateIssue::builder()
256                .project_id(project_id)
257                .subject("Attachment Test Issue")
258                .uploads(vec![UploadedAttachment {
259                    token: token.into(),
260                    filename: "README.md".into(),
261                    description: Some("Uploaded as part of unit test for redmine-api".into()),
262                    content_type: "application/octet-stream".into(),
263                }])
264                .build()?;
265            let IssueWrapper {
266                issue: created_issue,
267            } = redmine.json_response_body::<_, IssueWrapper<Issue>>(&create_issue_endpoint)?;
268
269            let get_issue_endpoint = GetIssue::builder()
270                .id(created_issue.id)
271                .include(vec![crate::api::issues::IssueInclude::Attachments])
272                .build()?;
273            let IssueWrapper { issue } =
274                redmine.json_response_body::<_, IssueWrapper<Issue>>(&get_issue_endpoint)?;
275            let attachment_id = issue.attachments.unwrap().first().unwrap().id;
276
277            let update_endpoint = UpdateAttachment::builder()
278                .id(attachment_id)
279                .attachment(AttachmentUpdate {
280                    filename: Some("new_readme.md".to_string()),
281                    description: Some("new description".to_string()),
282                })
283                .build()?;
284            redmine.ignore_response_body(&update_endpoint)?;
285
286            let get_endpoint = GetAttachment::builder().id(attachment_id).build()?;
287            let AttachmentWrapper { attachment } =
288                redmine.json_response_body::<_, AttachmentWrapper<Attachment>>(&get_endpoint)?;
289            assert_eq!(attachment.filename, "new_readme.md");
290            assert_eq!(attachment.description.unwrap(), "new description");
291
292            let delete_endpoint = DeleteAttachment::builder().id(attachment_id).build()?;
293            redmine.ignore_response_body(&delete_endpoint)?;
294
295            let get_issue_endpoint = GetIssue::builder()
296                .id(issue.id)
297                .include(vec![crate::api::issues::IssueInclude::Attachments])
298                .build()?;
299            let IssueWrapper { issue } =
300                redmine.json_response_body::<_, IssueWrapper<Issue>>(&get_issue_endpoint)?;
301            assert!(issue.attachments.is_none_or(|v| v.is_empty()));
302            Ok(())
303        })
304    }
305}