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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
use super::{Pollable, Result};
use crate::{impl_requester, Formality, Lang};
use serde::{Deserialize, Serialize};
use std::{
    future::IntoFuture,
    path::{Path, PathBuf},
};
use tokio::io::AsyncWriteExt;
use tokio_stream::StreamExt;

/// Response from api/v2/document
#[derive(Serialize, Deserialize)]
pub struct UploadDocumentResp {
    /// A unique ID assigned to the uploaded document and the translation process.
    /// Must be used when referring to this particular document in subsequent API requests.
    pub document_id: String,
    /// A unique key that is used to encrypt the uploaded document as well as the resulting
    /// translation on the server side. Must be provided with every subsequent API request
    /// regarding this particular document.
    pub document_key: String,
}

/// Response from api/v2/document/$ID
#[derive(Deserialize, Debug)]
pub struct DocumentStatusResp {
    /// A unique ID assigned to the uploaded document and the requested translation process.
    /// The same ID that was used when requesting the translation status.
    pub document_id: String,
    /// A short description of the state the document translation process is currently in.
    /// See [`DocumentTranslateStatus`] for more.
    pub status: DocumentTranslateStatus,
    /// Estimated number of seconds until the translation is done.
    /// This parameter is only included while status is "translating".
    pub seconds_remaining: Option<u64>,
    /// The number of characters billed to your account.
    pub billed_characters: Option<u64>,
    /// A short description of the error, if available. Note that the content is subject to change.
    /// This parameter may be included if an error occurred during translation.
    pub error_message: Option<String>,
}

/// Possible value of the document translate status
#[derive(Debug, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum DocumentTranslateStatus {
    /// The translation job is waiting in line to be processed
    Queued,
    /// The translation is currently ongoing
    Translating,
    /// The translation is done and the translated document is ready for download
    Done,
    /// An irrecoverable error occurred while translating the document
    Error,
}

impl DocumentTranslateStatus {
    pub fn is_done(&self) -> bool {
        self == &Self::Done
    }
}

impl_requester! {
    UploadDocumentRequester {
        @required{
            file_path: PathBuf,
            target_lang: Lang,
        };
        @optional{
            source_lang: Lang,
            filename: String,
            formality: Formality,
            glossary_id: String,
        };
    } -> Result<UploadDocumentResp, Error>;
}

impl<'a> UploadDocumentRequester<'a> {
    fn to_multipart_form(&self) -> reqwest::multipart::Form {
        let Self {
            source_lang,
            target_lang,
            formality,
            glossary_id,
            ..
        } = self;

        let mut form = reqwest::multipart::Form::new();

        // SET source_lang
        if let Some(lang) = source_lang {
            form = form.text("source_lang", lang.to_string());
        }

        // SET target_lang
        form = form.text("target_lang", target_lang.to_string());

        // SET formality
        if let Some(formal) = formality {
            form = form.text("formality", formal.to_string());
        }

        // SET glossary
        if let Some(id) = glossary_id {
            form = form.text("glossary_id", id.to_string());
        }

        form
    }

    fn send(&self) -> Pollable<'a, Result<UploadDocumentResp>> {
        let mut form = self.to_multipart_form();
        let client = self.client.clone();
        let filename = self.filename.clone();
        let file_path = self.file_path.clone();

        let fut = async move {
            // SET file && filename asynchronously
            let file = tokio::fs::read(&file_path).await.map_err(|err| {
                Error::ReadFileError(file_path.to_str().unwrap().to_string(), err)
            })?;

            let mut part = reqwest::multipart::Part::bytes(file);
            if let Some(filename) = filename {
                part = part.file_name(filename.to_string());
                form = form.text("filename", filename);
            } else {
                part = part.file_name(file_path.file_name().expect(
                    "No extension found for this file, and no filename given, cannot make request",
                ).to_str().expect("not a valid UTF-8 filepath!").to_string());
            }

            form = form.part("file", part);

            let res = client
                .post(client.get_endpoint("document"))
                .multipart(form)
                .send()
                .await
                .map_err(|err| Error::RequestFail(format!("fail to upload file: {err}")))?;

            if !res.status().is_success() {
                return super::extract_deepl_error(res).await;
            }

            let res: UploadDocumentResp = res.json().await.map_err(|err| {
                Error::InvalidResponse(format!("fail to decode response body: {err}"))
            })?;
            Ok(res)
        };

        Box::pin(fut)
    }
}

impl<'a> IntoFuture for UploadDocumentRequester<'a> {
    type Output = Result<UploadDocumentResp>;
    type IntoFuture = Pollable<'a, Self::Output>;

    fn into_future(self) -> Self::IntoFuture {
        self.send()
    }
}

impl<'a> IntoFuture for &mut UploadDocumentRequester<'a> {
    type Output = Result<UploadDocumentResp>;
    type IntoFuture = Pollable<'a, Self::Output>;

    fn into_future(self) -> Self::IntoFuture {
        self.send()
    }
}

impl DeepLApi {
    /// Upload document to DeepL API server, return [`UploadDocumentResp`] for
    /// querying the translation status and to download the translated document once
    /// translation is complete.
    ///
    /// # Example
    ///
    /// ```rust
    /// use deepl::DeepLApi;
    ///
    /// let key = std::env::var("DEEPL_API_KEY").unwrap();
    /// let deepl = DeepLApi::with(&key).new();
    ///
    /// // Upload the file to DeepL
    /// let filepath = std::path::PathBuf::from("./hamlet.txt");
    /// let response = deepl.upload_document(&filepath, Lang::ZH)
    ///         .source_lang(Lang::EN)
    ///         .filename("Hamlet.txt".to_string())
    ///         .formality(Formality::Default)
    ///         .glossary_id("def3a26b-3e84-45b3-84ae-0c0aaf3525f7".to_string())
    ///         .await
    ///         .unwrap();
    /// ```
    ///
    /// Read the example `upload_document` in repository for detailed usage
    pub fn upload_document(
        &self,
        fp: impl Into<std::path::PathBuf>,
        target_lang: Lang,
    ) -> UploadDocumentRequester {
        UploadDocumentRequester::new(self, fp.into(), target_lang)
    }

    async fn open_file_to_write(p: &Path) -> Result<tokio::fs::File> {
        let open_result = tokio::fs::OpenOptions::new()
            .append(true)
            .create_new(true)
            .open(p)
            .await;

        if let Ok(file) = open_result {
            return Ok(file);
        }

        let err = open_result.unwrap_err();
        if err.kind() != std::io::ErrorKind::AlreadyExists {
            return Err(Error::WriteFileError(format!(
                "Fail to open file {p:?}: {err}"
            )));
        }

        tokio::fs::remove_file(p).await.map_err(|err| {
            Error::WriteFileError(format!(
                "There was already a file there and it is not deletable: {err}"
            ))
        })?;
        dbg!("Detect exist, removed");

        let open_result = tokio::fs::OpenOptions::new()
            .append(true)
            .create_new(true)
            .open(p)
            .await;

        if let Err(err) = open_result {
            return Err(Error::WriteFileError(format!(
                "Fail to open file for download document, even after retry: {err}"
            )));
        }

        Ok(open_result.unwrap())
    }

    /// Check the status of document, returning [`DocumentStatusResp`] if success.
    pub async fn check_document_status(
        &self,
        ident: &UploadDocumentResp,
    ) -> Result<DocumentStatusResp> {
        let form = [("document_key", ident.document_key.as_str())];
        let url = self.get_endpoint(&format!("document/{}", ident.document_id));
        let res = self
            .post(url)
            .form(&form)
            .send()
            .await
            .map_err(|err| Error::RequestFail(err.to_string()))?;

        if !res.status().is_success() {
            return super::extract_deepl_error(res).await;
        }

        let status: DocumentStatusResp = res
            .json()
            .await
            .map_err(|err| Error::InvalidResponse(format!("response is not JSON: {err}")))?;

        Ok(status)
    }

    /// Download the possibly translated document. Downloaded document will store to the given
    /// `output` path.
    ///
    /// Return downloaded file's path if success
    pub async fn download_document<O: AsRef<Path>>(
        &self,
        ident: &UploadDocumentResp,
        output: O,
    ) -> Result<PathBuf> {
        let url = self.get_endpoint(&format!("document/{}/result", ident.document_id));
        let form = [("document_key", ident.document_key.as_str())];
        let res = self
            .post(url)
            .form(&form)
            .send()
            .await
            .map_err(|err| Error::RequestFail(err.to_string()))?;

        if res.status() == reqwest::StatusCode::NOT_FOUND {
            return Err(Error::NonExistDocument);
        }

        if res.status() == reqwest::StatusCode::SERVICE_UNAVAILABLE {
            return Err(Error::TranslationNotDone);
        }

        if !res.status().is_success() {
            return super::extract_deepl_error(res).await;
        }

        let mut file = Self::open_file_to_write(output.as_ref()).await?;

        let mut stream = res.bytes_stream();

        #[inline]
        fn mapper<E: std::error::Error>(s: &'static str) -> Box<dyn FnOnce(E) -> Error> {
            Box::new(move |err: E| Error::WriteFileError(format!("{s}: {err}")))
        }

        while let Some(chunk) = stream.next().await {
            let chunk = chunk.map_err(mapper("fail to download part of the document"))?;
            file.write_all(&chunk)
                .await
                .map_err(mapper("fail to write downloaded part into file"))?;
            file.sync_all()
                .await
                .map_err(mapper("fail to sync file content"))?;
        }

        Ok(output.as_ref().to_path_buf())
    }
}

#[tokio::test]
async fn test_upload_document() {
    let key = std::env::var("DEEPL_API_KEY").unwrap();
    let api = DeepLApi::with(&key).new();

    let raw_text = "Hello World";

    tokio::fs::write("./test.txt", &raw_text).await.unwrap();

    let test_file = PathBuf::from("./test.txt");
    let response = api.upload_document(&test_file, Lang::DE).await.unwrap();
    let mut status = api.check_document_status(&response).await.unwrap();

    // wait for translation
    loop {
        if status.status.is_done() {
            break;
        }
        if let Some(msg) = status.error_message {
            println!("{}", msg);
            break;
        }
        tokio::time::sleep(std::time::Duration::from_secs(3)).await;
        status = api.check_document_status(&response).await.unwrap();
        dbg!(&status);
    }

    let path = api
        .download_document(&response, "test_translated.txt")
        .await
        .unwrap();

    let content = tokio::fs::read_to_string(path).await.unwrap();
    let expect = "Hallo Welt";
    assert_eq!(content, expect);
}

#[tokio::test]
async fn test_upload_docx() {
    use docx_rs::{read_docx, DocumentChild, Docx, Paragraph, ParagraphChild, Run, RunChild};

    let key = std::env::var("DEEPL_API_KEY").unwrap();
    let api = DeepLApi::with(&key).new();

    let test_file = PathBuf::from("./example.docx");
    let file = std::fs::File::create(&test_file).expect("fail to create test asserts");
    Docx::new()
        .add_paragraph(
            Paragraph::new()
                .add_run(Run::new().add_text("To be, or not to be, that is the question")),
        )
        .build()
        .pack(file)
        .expect("fail to write test asserts");

    let response = api.upload_document(&test_file, Lang::DE).await.unwrap();
    let mut status = api.check_document_status(&response).await.unwrap();

    // wait for translation
    loop {
        if status.status.is_done() {
            break;
        }
        if let Some(msg) = status.error_message {
            println!("{}", msg);
            break;
        }
        tokio::time::sleep(std::time::Duration::from_secs(3)).await;
        status = api.check_document_status(&response).await.unwrap();
        dbg!(&status);
    }

    let path = api
        .download_document(&response, "translated.docx")
        .await
        .unwrap();
    let get = tokio::fs::read(&path).await.unwrap();
    let doc = read_docx(&get).expect("can not open downloaded document");
    // collect all the text in this docx file
    let text = doc
        .document
        .children
        .iter()
        .filter_map(|child| {
            if let DocumentChild::Paragraph(paragraph) = child {
                let text = paragraph
                    .children
                    .iter()
                    .filter_map(|pchild| {
                        if let ParagraphChild::Run(run) = pchild {
                            let text = run
                                .children
                                .iter()
                                .filter_map(|rchild| {
                                    if let RunChild::Text(text) = rchild {
                                        Some(text.text.to_string())
                                    } else {
                                        None
                                    }
                                })
                                .collect::<String>();

                            Some(text)
                        } else {
                            None
                        }
                    })
                    .collect::<String>();
                Some(text)
            } else {
                None
            }
        })
        .collect::<String>();

    assert_eq!(text, "Sein oder nicht sein, das ist hier die Frage");
}