philomena/lib/philomena_web/controllers/api/json/image_controller.ex

59 lines
1.5 KiB
Elixir
Raw Normal View History

2019-12-04 01:50:23 +01:00
defmodule PhilomenaWeb.Api.Json.ImageController do
use PhilomenaWeb, :controller
alias Philomena.Images.Image
alias Philomena.Images
alias Philomena.Interactions
2019-12-31 06:10:50 +01:00
alias Philomena.Repo
import Ecto.Query
2019-12-04 01:50:23 +01:00
2020-08-08 02:23:36 +02:00
plug PhilomenaWeb.ScraperCachePlug
plug PhilomenaWeb.ApiRequireAuthorizationPlug when action in [:create]
plug PhilomenaWeb.UserAttributionPlug when action in [:create]
plug PhilomenaWeb.ScraperPlug,
[params_name: "image", params_key: "image"] when action in [:create]
2019-12-31 06:10:50 +01:00
def show(conn, %{"id" => id}) do
user = conn.assigns.current_user
2019-12-31 06:10:50 +01:00
image =
Image
|> where(id: ^id)
|> preload([:user, :intensity, tags: :aliases])
2019-12-31 06:10:50 +01:00
|> Repo.one()
2019-12-04 01:50:23 +01:00
2019-12-31 06:10:50 +01:00
case image do
nil ->
conn
|> put_status(:not_found)
|> text("")
_ ->
interactions = Interactions.user_interactions([image], user)
render(conn, "show.json", image: image, interactions: interactions)
2019-12-31 06:10:50 +01:00
end
2019-12-04 01:50:23 +01:00
end
def create(conn, %{"image" => image_params}) do
attributes = conn.assigns.attributes
case Images.create_image(attributes, image_params) do
{:ok, %{image: image}} ->
2020-06-16 01:57:33 +02:00
PhilomenaWeb.Endpoint.broadcast!(
"firehose",
"image:create",
PhilomenaWeb.Api.Json.ImageView.render("show.json", %{image: image, interactions: []})
)
render(conn, "show.json", image: image, interactions: [])
{:error, :image, changeset, _} ->
conn
|> put_status(:bad_request)
|> render("error.json", changeset: changeset)
end
end
end