diff --git a/lib/outlook/translators/deepl.ex b/lib/outlook/translators/deepl.ex new file mode 100644 index 0000000..986a9f6 --- /dev/null +++ b/lib/outlook/translators/deepl.ex @@ -0,0 +1,77 @@ +defmodule Outlook.Translators.Deepl do + + def test(pid) do + for n <- 0..100 do + send(pid, {:progress, %{progress: n}}) + Process.sleep 50 + end + send(pid, {:progress, %{progress: nil}}) + end + + # @options [ssl: [{:versions, [:'tlsv1.2']}], recv_timeout: 500] + + @doc """ + Upload the content to translate and return document_id and document_key as Map. + """ + def start_translation %{auth_key: auth_key} = _credentials, content, target_lang do + form = get_multipart_form( + [ + {"target_lang", target_lang}, + {"file", content, {"form-data", [{:name, "file"}, {:filename, "datei.html"}]}, []} + ] + ) + + response_raw = HTTPoison.request!( + :post, + "https://api-free.deepl.com/v2/document", + form, + get_multipart_headers(auth_key) + ) + Jason.decode!(response_raw.body, keys: :atoms) + |> Map.put(:auth_key, auth_key) + end + + @doc """ + Upload the content to translate and return the estimated time until done. + """ + def check_status credentials do + response_raw = HTTPoison.request!( + :post, + "https://api-free.deepl.com/v2/document/#{credentials.document_id}", + get_multipart_form([{"document_key", credentials.document_key}]), + get_multipart_headers(credentials.auth_key) + ) + response = Jason.decode!(response_raw.body, keys: :atoms) + + case response do + %{status: "translating"} -> + Process.sleep(String.to_integer(response.seconds_remaining) * 1000) + check_status(credentials) + %{status: "done"} -> + response + end + end + + def get_translation credentials do + + response_raw = HTTPoison.request!( + :post, + "https://api-free.deepl.com/v2/document/#{credentials.document_id}/result", + get_multipart_form([{"document_key", credentials.document_key}]), + get_multipart_headers(credentials.auth_key) + ) + response_raw.body + end + + defp get_multipart_form fields do + {:multipart, fields} + end + + defp get_multipart_headers(auth_key) do + [ + "Authorization": "DeepL-Auth-Key #{auth_key}", + "Content-Type": "multipart/form-data", + "Transfer-Encoding": "chunked", + ] + end +end diff --git a/lib/outlook_web/live/translation_live/form_component.ex b/lib/outlook_web/live/translation_live/form_component.ex index b8e914e..d970608 100644 --- a/lib/outlook_web/live/translation_live/form_component.ex +++ b/lib/outlook_web/live/translation_live/form_component.ex @@ -39,6 +39,9 @@ defmodule OutlookWeb.TranslationLive.FormComponent do