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    /// creates a project with an issue with an attachment and calls the
174    /// function with the attachment id
175    fn with_attachment<F>(name: &str, f: F) -> Result<(), Box<dyn Error>>
176    where
177        F: FnOnce(&crate::api::Redmine, u64) -> Result<(), Box<dyn Error>>,
178    {
179        use crate::api::issues::{
180            CreateIssue, GetIssue, Issue, IssueWrapper, UploadedAttachment, test::ISSUES_LOCK,
181        };
182        use crate::api::test_helpers::with_project;
183        use crate::api::uploads::{FileUploadToken, UploadFile, UploadWrapper};
184
185        let _w_issues = ISSUES_LOCK.blocking_write();
186        with_project(name, |redmine, project_id, _| {
187            let upload_endpoint = UploadFile::builder().file("README.md").build()?;
188            let UploadWrapper {
189                upload: FileUploadToken { id: _, token },
190            } = redmine
191                .json_response_body::<_, UploadWrapper<FileUploadToken>>(&upload_endpoint)?;
192            let create_issue_endpoint = CreateIssue::builder()
193                .project_id(project_id)
194                .subject("Attachment Test Issue")
195                .uploads(vec![UploadedAttachment {
196                    token: token.into(),
197                    filename: "README.md".into(),
198                    description: Some("Uploaded as part of unit test for redmine-api".into()),
199                    content_type: "application/octet-stream".into(),
200                }])
201                .build()?;
202            let IssueWrapper {
203                issue: created_issue,
204            } = redmine.json_response_body::<_, IssueWrapper<Issue>>(&create_issue_endpoint)?;
205
206            let get_issue_endpoint = GetIssue::builder()
207                .id(created_issue.id)
208                .include(vec![crate::api::issues::IssueInclude::Attachments])
209                .build()?;
210            let IssueWrapper { issue } =
211                redmine.json_response_body::<_, IssueWrapper<Issue>>(&get_issue_endpoint)?;
212            let attachment_id = issue
213                .attachments
214                .and_then(|a| a.first().map(|a| a.id))
215                .ok_or("created issue has no attachment")?;
216            f(redmine, attachment_id)
217        })
218    }
219
220    #[traced_test]
221    #[test]
222    fn test_get_attachment() -> Result<(), Box<dyn Error>> {
223        with_attachment("test_get_attachment", |redmine, attachment_id| {
224            let endpoint = GetAttachment::builder().id(attachment_id).build()?;
225            redmine.json_response_body::<_, AttachmentWrapper<Attachment>>(&endpoint)?;
226            Ok(())
227        })
228    }
229
230    /// this tests if any of the results contain a field we are not deserializing
231    ///
232    /// this will only catch fields we missed if they are part of the response but
233    /// it is better than nothing
234    #[traced_test]
235    #[test]
236    fn test_completeness_attachment_type() -> Result<(), Box<dyn Error>> {
237        with_attachment(
238            "test_completeness_attachment_type",
239            |redmine, attachment_id| {
240                let endpoint = GetAttachment::builder().id(attachment_id).build()?;
241                let AttachmentWrapper { attachment: value } = redmine
242                    .json_response_body::<_, AttachmentWrapper<serde_json::Value>>(&endpoint)?;
243                let o: Attachment = serde_json::from_value(value.clone())?;
244                let reserialized = serde_json::to_value(o)?;
245                assert_eq!(value, reserialized);
246                Ok(())
247            },
248        )
249    }
250
251    #[traced_test]
252    #[test]
253    fn test_update_delete_attachment() -> Result<(), Box<dyn Error>> {
254        use crate::api::issues::{
255            CreateIssue, GetIssue, Issue, IssueWrapper, UploadedAttachment, test::ISSUES_LOCK,
256        };
257        use crate::api::test_helpers::with_project;
258        use crate::api::uploads::{FileUploadToken, UploadFile, UploadWrapper};
259
260        let _w_issues = ISSUES_LOCK.blocking_write();
261        with_project("test_update_delete_attachment", |redmine, project_id, _| {
262            let upload_endpoint = UploadFile::builder().file("README.md").build()?;
263            let UploadWrapper {
264                upload: FileUploadToken { id: _, token },
265            } = redmine
266                .json_response_body::<_, UploadWrapper<FileUploadToken>>(&upload_endpoint)?;
267            let create_issue_endpoint = CreateIssue::builder()
268                .project_id(project_id)
269                .subject("Attachment Test Issue")
270                .uploads(vec![UploadedAttachment {
271                    token: token.into(),
272                    filename: "README.md".into(),
273                    description: Some("Uploaded as part of unit test for redmine-api".into()),
274                    content_type: "application/octet-stream".into(),
275                }])
276                .build()?;
277            let IssueWrapper {
278                issue: created_issue,
279            } = redmine.json_response_body::<_, IssueWrapper<Issue>>(&create_issue_endpoint)?;
280
281            let get_issue_endpoint = GetIssue::builder()
282                .id(created_issue.id)
283                .include(vec![crate::api::issues::IssueInclude::Attachments])
284                .build()?;
285            let IssueWrapper { issue } =
286                redmine.json_response_body::<_, IssueWrapper<Issue>>(&get_issue_endpoint)?;
287            let attachment_id = issue.attachments.unwrap().first().unwrap().id;
288
289            let update_endpoint = UpdateAttachment::builder()
290                .id(attachment_id)
291                .attachment(AttachmentUpdate {
292                    filename: Some("new_readme.md".to_string()),
293                    description: Some("new description".to_string()),
294                })
295                .build()?;
296            redmine.ignore_response_body(&update_endpoint)?;
297
298            let get_endpoint = GetAttachment::builder().id(attachment_id).build()?;
299            let AttachmentWrapper { attachment } =
300                redmine.json_response_body::<_, AttachmentWrapper<Attachment>>(&get_endpoint)?;
301            assert_eq!(attachment.filename, "new_readme.md");
302            assert_eq!(attachment.description.unwrap(), "new description");
303
304            let delete_endpoint = DeleteAttachment::builder().id(attachment_id).build()?;
305            redmine.ignore_response_body(&delete_endpoint)?;
306
307            let get_issue_endpoint = GetIssue::builder()
308                .id(issue.id)
309                .include(vec![crate::api::issues::IssueInclude::Attachments])
310                .build()?;
311            let IssueWrapper { issue } =
312                redmine.json_response_body::<_, IssueWrapper<Issue>>(&get_issue_endpoint)?;
313            assert!(issue.attachments.is_none_or(|v| v.is_empty()));
314            Ok(())
315        })
316    }
317}