8.8 KiB · text History e569b6d
defmodule CartosnapAppWeb.UploadLive do
  @moduledoc """
  Adding photos. Files are dropped or picked, uploaded to the server, then
  taken in by `CartosnapApp.Photos.ingest_upload/4`: the original is stored,
  its EXIF, location and blurhash are read, and resizing is queued.

  Uploads can go straight into a trip (any trip the uploader owns or is a
  member of), picked here or preset by `?trip=<id>` (a trip's Add photos).
  """
  use CartosnapAppWeb, :live_view

  require Logger

  alias CartosnapApp.Photos
  alias CartosnapApp.Trips
  alias CartosnapApp.Photos.Photo

  @max_entries 30
  @max_file_size 60_000_000

  @impl true
  def mount(params, _session, socket) do
    scope = socket.assigns.current_scope
    options = Trips.trip_options(scope)
    trip_id = params["trip"]
    trip_id = if Enum.any?(options, fn {_name, id} -> id == trip_id end), do: trip_id, else: ""

    {:ok,
     socket
     |> assign(:page_title, "Upload")
     |> assign(:trip_options, options)
     |> assign(:trip_form, to_form(%{"trip_id" => trip_id}, as: :upload))
     |> assign(:uploaded_count, 0)
     |> assign(:max_entries, @max_entries)
     |> assign(:max_file_size, @max_file_size)
     |> stream(:uploaded, [])
     |> allow_upload(:photos,
       accept: ~w(.jpg .jpeg .png .gif),
       max_entries: @max_entries,
       max_file_size: @max_file_size
     )}
  end

  @impl true
  def render(assigns) do
    ~H"""
    <Layouts.app flash={@flash} current_scope={@current_scope} active={:upload}>
      <.header>
        Upload
        <:subtitle>
          JPEG, PNG or GIF, up to {@max_entries} at a time. Photos with GPS data land on the map.
        </:subtitle>
      </.header>

      <form id="upload-form" phx-submit="save" phx-change="validate" class="space-y-4">
        <label
          for={@uploads.photos.ref}
          phx-drop-target={@uploads.photos.ref}
          id="upload-drop"
          class="group flex cursor-pointer flex-col items-center justify-center gap-3 rounded-box border-2 border-dashed border-base-300 bg-base-200/50 px-6 py-14 text-center transition hover:border-primary hover:bg-primary/5 [&.phx-drop-target-active]:border-primary [&.phx-drop-target-active]:bg-primary/10"
        >
          <span class="grid size-14 place-items-center rounded-2xl bg-primary/15 text-primary transition-transform group-hover:-translate-y-1">
            <.icon name="hero-arrow-up-tray" class="size-7" />
          </span>
          <span class="font-medium">Drop photos here, or click to choose</span>
          <span class="text-xs text-base-content/60">Up to {div(@max_file_size, 1_000_000)} MB each</span>
          <.live_file_input upload={@uploads.photos} class="sr-only" />
        </label>

        <p :for={err <- upload_errors(@uploads.photos)} class="alert alert-error alert-soft text-sm">
          {error_to_string(err)}
        </p>

        <div
          :if={@uploads.photos.entries != []}
          id="upload-entries"
          class="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-5"
        >
          <div
            :for={entry <- @uploads.photos.entries}
            id={"entry-#{entry.ref}"}
            class="relative overflow-hidden rounded-box border border-base-300 bg-base-100"
          >
            <.live_img_preview entry={entry} class="aspect-[4/3] w-full object-cover" />
            <div class="space-y-1.5 p-2">
              <p class="truncate text-xs" title={entry.client_name}>{entry.client_name}</p>
              <progress
                class="progress progress-primary h-1.5 w-full"
                value={entry.progress}
                max="100"
              >
                {entry.progress}%
              </progress>
              <p :for={err <- upload_errors(@uploads.photos, entry)} class="text-xs text-error">
                {error_to_string(err)}
              </p>
            </div>
            <button
              type="button"
              phx-click="cancel"
              phx-value-ref={entry.ref}
              aria-label={"Remove #{entry.client_name}"}
              class="btn btn-circle btn-xs absolute right-1.5 top-1.5 border-0 bg-black/50 text-white hover:bg-black/70"
            >
              <.icon name="hero-x-mark-micro" class="size-3.5" />
            </button>
          </div>
        </div>

        <div class="flex flex-wrap items-end gap-3">
          <div :if={@trip_options != []} class="w-full max-w-xs">
            <.input
              field={@trip_form[:trip_id]}
              type="select"
              label="Into a trip"
              prompt="No trip, just my photos"
              options={@trip_options}
            />
          </div>
          <button
            type="submit"
            id="upload-submit"
            class="btn btn-primary"
            disabled={@uploads.photos.entries == []}
            phx-disable-with="Uploading…"
          >
            <.icon name="hero-cloud-arrow-up-micro" class="size-4" />
            Upload {length(@uploads.photos.entries)} {if length(@uploads.photos.entries) == 1,
              do: "photo",
              else: "photos"}
          </button>
        </div>
      </form>

      <section :if={@uploaded_count > 0} class="space-y-3">
        <div class="flex items-baseline justify-between">
          <h2 class="font-semibold">Added this visit</h2>
          <%= case trip_name(@trip_options, @trip_form[:trip_id].value) do %>
            <% nil -> %>
              <.link navigate={~p"/photos"} class="link link-primary text-sm">See them all →</.link>
            <% name -> %>
              <.link
                navigate={~p"/trips/#{@trip_form[:trip_id].value}"}
                class="link link-primary text-sm"
                id="see-trip"
              >
                See {name} →
              </.link>
          <% end %>
        </div>
        <div
          id="uploaded"
          phx-update="stream"
          class="grid grid-cols-3 gap-2 sm:grid-cols-6 lg:grid-cols-8"
        >
          <.link
            :for={{dom_id, photo} <- @streams.uploaded}
            id={dom_id}
            navigate={~p"/photos/#{photo}"}
            class="flex aspect-square items-center justify-center rounded-field bg-base-200 p-1 text-center text-[10px] leading-tight text-base-content/70 transition hover:bg-base-300"
            title={Photo.title(photo)}
          >
            <span class="line-clamp-3 break-all">{Photo.title(photo)}</span>
          </.link>
        </div>
      </section>
    </Layouts.app>
    """
  end

  @impl true
  def handle_event("validate", params, socket) do
    case params do
      %{"upload" => %{"trip_id" => trip_id}} ->
        {:noreply, assign(socket, :trip_form, to_form(%{"trip_id" => trip_id}, as: :upload))}

      _ ->
        {:noreply, socket}
    end
  end

  def handle_event("cancel", %{"ref" => ref}, socket) do
    {:noreply, cancel_upload(socket, :photos, ref)}
  end

  def handle_event("save", params, socket) do
    scope = socket.assigns.current_scope

    trip_id =
      case get_in(params, ["upload", "trip_id"]) || socket.assigns.trip_form[:trip_id].value do
        id when is_binary(id) and id != "" -> id
        _ -> nil
      end

    results =
      consume_uploaded_entries(socket, :photos, fn %{path: path}, entry ->
        case Photos.ingest_upload(scope, path, entry, trip_id: trip_id) do
          {:ok, photo} ->
            {:ok, {:ok, photo}}

          {:error, reason} ->
            Logger.warning("upload of #{entry.client_name} failed: #{inspect(reason)}")
            {:ok, {:error, entry.client_name}}
        end
      end)

    photos = for {:ok, photo} <- results, do: photo
    failed = for {:error, name} <- results, do: name

    socket =
      socket
      |> stream(:uploaded, photos, at: 0)
      |> update(:uploaded_count, &(&1 + length(photos)))
      |> flash_result(photos, failed)

    {:noreply, socket}
  end

  defp flash_result(socket, [], []),
    do: put_flash(socket, :error, "Pick some photos first.")

  defp flash_result(socket, photos, []),
    do:
      put_flash(
        socket,
        :info,
        "Added #{plural(length(photos))}. Thumbnails will appear as they're made."
      )

  defp flash_result(socket, photos, failed) do
    put_flash(
      socket,
      :error,
      "Added #{plural(length(photos))}; couldn't store #{Enum.join(failed, ", ")}. Try those again."
    )
  end

  defp trip_name(options, id) do
    Enum.find_value(options, fn {name, trip_id} -> if trip_id == id, do: name end)
  end

  defp plural(1), do: "1 photo"
  defp plural(n), do: "#{n} photos"

  defp error_to_string(:too_large), do: "That file is too large"
  defp error_to_string(:too_many_files), do: "That's more than #{@max_entries} files at once"
  defp error_to_string(:not_accepted), do: "Only JPEG, PNG and GIF images"
  defp error_to_string(:external_client_failure), do: "The upload failed; try again"
  defp error_to_string(other), do: "Upload error: #{other}"
end