philomena/lib/philomena_web/plugs/scraper_plug.ex

44 lines
1.2 KiB
Elixir
Raw Normal View History

2019-11-29 00:19:47 +01:00
defmodule PhilomenaWeb.ScraperPlug do
def init(opts), do: opts
def call(conn, opts) do
2019-12-19 00:51:02 +01:00
params_name = Keyword.get(opts, :params_name, "image")
params_key = Keyword.get(opts, :params_key, "image")
2019-11-29 00:19:47 +01:00
case conn.params do
2019-12-19 00:51:02 +01:00
%{^params_name => %{^params_key => %Plug.Upload{}}} ->
conn
2020-01-11 19:50:53 +01:00
%{"scraper_cache" => url} when not is_nil(url) ->
Philomena.Http.get!(url)
2019-11-29 00:19:47 +01:00
|> maybe_fixup_params(opts, conn)
_ ->
conn
end
end
defp maybe_fixup_params(%Tesla.Env{body: body, status: 200}, opts, conn) do
2019-11-29 00:19:47 +01:00
params_name = Keyword.get(opts, :params_name, "image")
params_key = Keyword.get(opts, :params_key, "image")
file = Briefly.create!()
now = DateTime.utc_now() |> DateTime.to_unix(:microsecond)
File.write!(file, body)
2020-01-11 05:20:19 +01:00
fake_upload = %Plug.Upload{
path: file,
content_type: "application/octet-stream",
filename: "scraper-#{now}"
}
2019-11-29 00:19:47 +01:00
2020-01-11 05:20:19 +01:00
updated_form = Map.put(conn.params[params_name], params_key, fake_upload)
2019-11-29 00:19:47 +01:00
2020-01-11 05:20:19 +01:00
updated_params = Map.put(conn.params, params_name, updated_form)
2019-11-29 00:19:47 +01:00
%{conn | params: updated_params}
end
2020-01-11 05:20:19 +01:00
2019-11-29 00:19:47 +01:00
defp maybe_fixup_params(_response, _opts, conn), do: conn
2019-12-19 00:51:02 +01:00
end