Files
phoenix-ausblick/lib/outlook/translators/deepl.ex
2023-01-05 22:19:23 +01:00

78 lines
2.1 KiB
Elixir

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