1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
use crate::authentication::Authentication;
use crate::data::MediaItem;
use crate::error::Error as ImageVaultError;
use crate::Client;
use serde::Serialize;
use std::fs::metadata;
use std::path::Path;

const STORE_CONTENT_ENDPOINT: &'static str = "apiv2/mediacontentservice/storecontentinvault";

/// Calls `mediacontentservice/storecontentinvault`.
///
/// File name and content type will be set from the path.
///
/// Returns an `AuthenticationMissing` error
/// if the `Client` does not have any `Authentication` set.
///
/// ## Arguments
/// * `client` - The ImageVault `Client` to use.
/// * `path` - Path to stored file, for getting name and content type.
/// * `upload_file_id` - The file id to store, returned from `upload_service/upload`.
/// * `vault_id` - The vault to store the content in.
///
/// ## Examples
///
/// ```
/// use std::path::Path;
/// use imagevault::{
///     service::media_content_service,
///     service::upload_service,
///     Client,
///     authentication::ClientCredentialsAuthentication
/// };
///
/// # async fn test() -> Result<(), imagevault::error::Error> {
/// let authentication = ClientCredentialsAuthentication::default();
/// let client = Client::new(
///     "identity",
///     "secret",
///     "https://myimagevault.local"
///     )?
///     .with_authentication(authentication);
///
/// // Upload a file
/// let file_path = Path::new("my_image.jpg");
/// let upload_file_id = upload_service::upload_from_path(
///     &client,
///     file_path
///     )
///     .await?;
///
/// // Store uploaded content in vault 42
/// let media_item = media_content_service::store_content_in_vault_from_path(
///     &client,
///     file_path,
///     &upload_file_id,
///     42
///     )
///     .await?;
/// # Ok(())
/// # }
/// ```
pub async fn store_content_in_vault_from_path<T: Authentication + Sync>(
    client: &Client<T>,
    path: &Path,
    upload_file_id: &str,
    vault_id: u64,
) -> Result<MediaItem, ImageVaultError> {
    let _md = metadata(path)?;
    let os_file_name = path.file_name().ok_or(std::io::Error::new(
        std::io::ErrorKind::InvalidData,
        "Not a file",
    ))?;
    let file_name = os_file_name.to_str().ok_or(std::io::Error::new(
        std::io::ErrorKind::InvalidData,
        "File name has invalid characters",
    ))?;
    let mime_type = mime_guess::from_path(path)
        .first()
        .ok_or(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            "Unable to guess mime type for this file, use store_content_in_vault to specify parameters explicitly"))?;
    store_content_in_vault(
        client,
        file_name,
        &mime_type.to_string(),
        upload_file_id,
        vault_id,
    )
    .await
}

/// Calls `mediacontentservice/storecontentinvault`.
///
/// Returns an `AuthenticationMissing` error
/// if the `Client` does not have any `Authentication` set.
///
/// ## Arguments
/// * `client` - The ImageVault `Client` to use.
/// * `file_name` - The name of the file.
/// * `content_type` - The content type.
/// * `upload_file_id` - The file id to store, returned from `upload_service/upload`.
/// * `vault_id` - The vault to store the content in.
///
/// ## Examples
///
/// ```
/// use std::path::Path;
/// use imagevault::{
///     service::media_content_service,
///     service::upload_service,
///     Client,
///     authentication::ClientCredentialsAuthentication
/// };
///
/// # async fn test() -> Result<(), imagevault::error::Error> {
/// let authentication = ClientCredentialsAuthentication::default();
/// let client = Client::new(
///     "identity",
///     "secret",
///     "https://myimagevault.local"
///     )?
///     .with_authentication(authentication);
///
/// // Upload a file
/// let file_path = Path::new("my_image.jpg");
/// let upload_file_id = upload_service::upload_from_path(
///     &client,
///     file_path
///     )
///     .await?;
///
/// // Store uploaded content in vault 42
/// let media_item = media_content_service::store_content_in_vault(
///     &client,
///     "my_image.jpg",
///     "image/jpeg",
///     &upload_file_id,
///     42
///     )
///     .await?;
/// # Ok(())
/// # }
/// ```
pub async fn store_content_in_vault<T: Authentication + Sync>(
    client: &Client<T>,
    file_name: &str,
    content_type: &str,
    upload_file_id: &str,
    vault_id: u64,
) -> Result<MediaItem, ImageVaultError> {
    let full_url = client.base_url.join(STORE_CONTENT_ENDPOINT)?;
    let auth_unwrapped = client
        .authentication
        .as_ref()
        .ok_or_else(|| ImageVaultError::AuthenticationMissing)?;
    let auth_header = auth_unwrapped
        .lock()
        .await
        .authenticate(
            &client.client_identity,
            &client.client_secret,
            &client.base_url,
            &client.reqwest_client,
        )
        .await?;
    let data = StoreContentInVaultRequest {
        upload_file_id: upload_file_id.to_string(),
        file_name: file_name.to_string(),
        content_type: content_type.to_string(),
        vault_id,
    };

    let response = client
        .reqwest_client
        .post(full_url)
        .bearer_auth(auth_header)
        .json(&data)
        .send()
        .await?;
    if let Err(err) = response.error_for_status_ref() {
        return Err(err.into());
    } else {
        return Ok(response.json::<MediaItem>().await?);
    }
}

#[derive(Serialize, Debug)]
#[serde(rename_all = "camelCase")]
struct StoreContentInVaultRequest {
    upload_file_id: String,
    #[serde(rename = "filename")]
    file_name: String,
    content_type: String,
    vault_id: u64,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::authentication::DummyAuth;
    use crate::testutil;
    #[test]
    fn media_service_store_content_in_vault_test() {
        let rt = tokio::runtime::Runtime::new().unwrap();
        rt.block_on(async {
            let mock = mockito::mock("POST", mockito::Matcher::Any)
                .expect(1)
                .with_status(200)
                .with_header("content-type", "application/json")
                .with_body(testutil::get_test_data("store_content_in_vault_response"))
                .create();
            let authentication = DummyAuth::new();
            let client = Client::new("client_identity", "client_secret", &mockito::server_url())
                .unwrap()
                .with_authentication(authentication);
            let media_item = store_content_in_vault(
                &client,
                "some_file.jpg",
                "image/jpeg",
                "upload_file_id",
                42,
            )
            .await;
            assert!(media_item.is_ok());
            mock.assert();
        });
    }
    #[test]
    fn media_service_store_content_in_vault_from_path_test() {
        let rt = tokio::runtime::Runtime::new().unwrap();
        rt.block_on(async {
            let mock = mockito::mock("POST", mockito::Matcher::Any)
                .expect(1)
                .with_status(200)
                .with_header("content-type", "application/json")
                .with_body(testutil::get_test_data("store_content_in_vault_response"))
                .create();
            let authentication = DummyAuth::new();
            let client = Client::new("client_identity", "client_secret", &mockito::server_url())
                .unwrap()
                .with_authentication(authentication);
            let media_item = store_content_in_vault_from_path(
                &client,
                &testutil::get_jpg_test_image_path(),
                "upload_file_id",
                42,
            )
            .await;
            assert!(media_item.is_ok());
            mock.assert();
        });
    }
}