~ihabunek/triglav

ref: 3a1876166aa129c76c1b09fc562af764d04df4e1 triglav/lib/triglav/http.ex -rw-r--r-- 1.2 KiB
3a187616Ivan Habunek Fix detecting unexpected master route members 7 months ago
                                                                                
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
defmodule Triglav.Http do
  require Logger

  def get(url) do
    with {:ok, {{'HTTP/1.1', 200, 'OK'}, _headers, body}} <-
           :httpc.request(:get, {to_charlist(url), []}, [], []) do
      {:ok, to_string(body)}
    end
  end

  @spec download(String.t(), String.t(), Keyword.t()) :: {:ok, String.t()} | {:error, term()}
  def download(url, target_dir, opts \\ []) do
    default_filename =
      url
      |> URI.parse()
      |> Map.fetch!(:path)
      |> Path.basename()

    overwrite? = Keyword.get(opts, :overwrite, false)
    filename = Keyword.get(opts, :filename, default_filename)
    path = Path.join(target_dir, filename)
    exists? = File.exists?(path)

    with :ok <- maybe_delete(path, exists?, overwrite?),
         :ok <- do_download(url, path) do
      {:ok, path}
    end
  end

  defp maybe_delete(_, false, _), do: :ok
  defp maybe_delete(_, true, false), do: {:error, :file_exists}
  defp maybe_delete(path, true, true), do: File.rm(path)

  defp do_download(url, target) do
    Logger.info("Downloading #{url} to #{target}")

    case :httpc.request(:get, {to_charlist(url), []}, [], stream: to_charlist(target)) do
      {:ok, :saved_to_file} -> :ok
    end
  end
end