2.7 KiB · text History e569b6d
defmodule CartosnapAppWeb.Api.V1.PhotoController do
  @moduledoc """
  `POST /api/v1/photos`: one photo from the device, as multipart:

    * `photo` - the image file (required);
    * `client_ref` - the device's own id for this upload (required): sent
      again on a retry, it gets back the photo the first attempt made
      (`200`, `"duplicate": true`) rather than storing it twice;
    * `trip_id` - a trip to add it to (optional).

  `201` with the photo when it's new. A trip the user can no longer add to
  (deleted, or they left it) doesn't lose the photo: it's kept among their
  own photos, and the answer says `"trip_id": null, "trip_unavailable":
  true`, so the app can say so.
  """
  use CartosnapAppWeb, :controller

  alias CartosnapApp.Photos
  alias CartosnapApp.Trips
  alias CartosnapAppWeb.Api.ErrorJSON

  @max_ref 100

  def create(conn, %{"photo" => %Plug.Upload{} = upload, "client_ref" => ref} = params)
      when is_binary(ref) and byte_size(ref) in 1..@max_ref do
    scope = conn.assigns.current_scope

    {trip_id, unavailable?} = resolve_trip(scope, params["trip_id"])

    if image?(upload) do
      entry = %{client_name: upload.filename || "photo.jpg", client_type: upload.content_type}

      case Photos.ingest_upload(scope, upload.path, entry, client_ref: ref, trip_id: trip_id) do
        {:ok, photo} ->
          conn |> put_status(:created) |> json(body(photo, trip_id, unavailable?, false))

        {:ok, photo, :existing} ->
          json(conn, body(photo, trip_id, unavailable?, true))

        {:error, _reason} ->
          error(conn, :internal_server_error, :upload_failed)
      end
    else
      error(conn, :unsupported_media_type, :unsupported_media_type)
    end
  end

  def create(conn, _params), do: error(conn, :bad_request, :bad_request)

  # `{trip_id, unavailable?}`: the trip to file under, if the user can.
  defp resolve_trip(scope, id) when is_binary(id) and id != "" do
    case Trips.fetch_trip(scope, id) do
      {:ok, trip} -> {trip.id, false}
      :error -> {nil, true}
    end
  end

  defp resolve_trip(_scope, _id), do: {nil, false}

  defp image?(%Plug.Upload{content_type: "image/" <> _}), do: true

  defp image?(%Plug.Upload{filename: name}) when is_binary(name),
    do: String.downcase(Path.extname(name)) in ~w(.jpg .jpeg .png .gif .heic .webp)

  defp image?(_upload), do: false

  defp body(photo, trip_id, unavailable?, duplicate?) do
    %{
      photo: %{id: photo.id, filename: photo.filename, url: url(~p"/photos/#{photo}")},
      trip_id: trip_id,
      trip_unavailable: unavailable?,
      duplicate: duplicate?
    }
  end

  defp error(conn, status, code), do: conn |> put_status(status) |> json(ErrorJSON.error(code))
end