2019-12-04 02:27:58 +01:00
|
|
|
defmodule PhilomenaWeb.Api.Json.OembedController do
|
|
|
|
use PhilomenaWeb, :controller
|
|
|
|
|
|
|
|
alias Philomena.Images.Image
|
|
|
|
alias Philomena.Repo
|
|
|
|
import Ecto.Query
|
|
|
|
|
|
|
|
@cdn_regex ~r/\/img\/.*\/(\d+)(\.|[\/_][_\w])/
|
|
|
|
@img_regex ~r/\/(\d+)/
|
|
|
|
|
|
|
|
def index(conn, %{"url" => url}) do
|
|
|
|
parsed = URI.parse(url)
|
|
|
|
|
|
|
|
try_oembed(conn, parsed)
|
|
|
|
end
|
2020-01-11 05:20:19 +01:00
|
|
|
|
2019-12-04 02:27:58 +01:00
|
|
|
def index(conn, _params), do: oembed_error(conn)
|
|
|
|
|
|
|
|
defp try_oembed(conn, %{path: path}) do
|
|
|
|
cdn = Regex.run(@cdn_regex, path, capture: :all_but_first)
|
|
|
|
img = Regex.run(@img_regex, path, capture: :all_but_first)
|
|
|
|
|
|
|
|
image_id =
|
|
|
|
cond do
|
2020-01-11 05:20:19 +01:00
|
|
|
cdn -> hd(cdn)
|
|
|
|
img -> hd(img)
|
2019-12-04 02:27:58 +01:00
|
|
|
true -> nil
|
|
|
|
end
|
|
|
|
|
2021-02-11 02:01:05 +01:00
|
|
|
image_id
|
|
|
|
|> load_image()
|
2019-12-04 02:27:58 +01:00
|
|
|
|> oembed_image(conn)
|
|
|
|
end
|
|
|
|
|
|
|
|
defp load_image(nil), do: nil
|
2020-01-11 05:20:19 +01:00
|
|
|
|
2019-12-04 02:27:58 +01:00
|
|
|
defp load_image(id) do
|
|
|
|
Image
|
|
|
|
|> where(id: ^id, hidden_from_users: false)
|
2020-12-03 20:23:32 +01:00
|
|
|
|> preload([:user, tags: :aliases])
|
2019-12-04 02:27:58 +01:00
|
|
|
|> Repo.one()
|
|
|
|
end
|
|
|
|
|
|
|
|
defp oembed_image(nil, conn), do: oembed_error(conn)
|
2021-02-11 02:01:05 +01:00
|
|
|
defp oembed_image(image, conn), do: render(conn, "show.json", image: image)
|
2019-12-04 02:27:58 +01:00
|
|
|
|
|
|
|
defp oembed_error(conn) do
|
|
|
|
conn
|
|
|
|
|> Plug.Conn.put_status(:not_found)
|
2021-02-11 02:01:05 +01:00
|
|
|
|> render("error.json")
|
2019-12-04 02:27:58 +01:00
|
|
|
end
|
2020-01-11 05:20:19 +01:00
|
|
|
end
|