3.0 KiB · text History e569b6d
defmodule CartosnapApp.Workers.ProcessImage do
  @moduledoc """
  Makes a photo's full, preview and thumbnail variants from its original
  and records them, with its shape (size, and whether it's a photo sphere
  or panorama). Queued by `CartosnapApp.Photos.ingest_upload/4`.

  Unique per photo while queued, so re-queueing (`enqueue_missing/0`) never
  doubles up the work. A photo deleted before its turn is skipped.
  """

  use Oban.Worker,
    queue: :images,
    max_attempts: 5,
    unique: [keys: [:id], states: [:available, :scheduled, :retryable]]

  import Ecto.Query, only: [from: 2]

  alias CartosnapApp.Photos
  alias CartosnapApp.Photos.{Images, Photo}
  alias CartosnapApp.Repo
  alias CartosnapApp.Storage

  @impl Oban.Worker
  def perform(%Oban.Job{args: %{"id" => id}}) do
    case Repo.get(Photo, id) do
      nil -> {:cancel, :photo_deleted}
      photo -> process(photo)
    end
  end

  @impl Oban.Worker
  def timeout(_job), do: :timer.minutes(5)

  @doc """
  Queues every photo that is missing a variant: the recovery path after a
  failed batch. Returns how many were queued.
  """
  def enqueue_missing do
    from(p in Photo,
      where: is_nil(p.url_full) or is_nil(p.url_preview) or is_nil(p.url_thumb),
      select: p.id
    )
    |> Repo.all()
    |> Enum.map(&new(%{id: &1}))
    |> Oban.insert_all()
    |> length()
  end

  @doc """
  Queues every photo again: for working out what a newer pipeline knows
  about photos uploaded before it (their shape, say). In a running
  release: `bin/cartosnap_app rpc "CartosnapApp.Workers.ProcessImage.enqueue_all()"`.
  """
  def enqueue_all do
    from(p in Photo, select: p.id)
    |> Repo.all()
    |> Enum.map(&new(%{id: &1}))
    |> Oban.insert_all()
    |> length()
  end

  defp process(photo) do
    ext = Photo.ext(photo)
    original = Path.join(System.tmp_dir!(), "cartosnap-#{photo.id}-orig.#{ext}")

    try do
      with {:ok, body} <- Storage.get(photo.url_original),
           :ok <- File.write(original, body) do
        shape = Images.shape(original)
        variants = Images.variants(original)

        try do
          upload_variants(photo, ext, variants, shape)
        after
          Enum.each(variants, fn {_variant, path} -> File.rm(path) end)
        end
      end
    after
      File.rm(original)
    end
  end

  defp upload_variants(photo, ext, variants, shape) do
    keys =
      Enum.reduce_while(variants, %{}, fn {variant, path}, acc ->
        key = Storage.key(photo, to_string(variant), ext)

        case Storage.put(key, File.read!(path), Images.content_type(ext)) do
          :ok -> {:cont, Map.put(acc, variant, key)}
          {:error, reason} -> {:halt, {:error, reason}}
        end
      end)

    with %{} <- keys,
         {:ok, _photo} <-
           Photos.put_variants(
             photo,
             Map.merge(shape, %{
               url_full: keys.full,
               url_preview: keys.prev,
               url_thumb: keys.thumb
             })
           ) do
      :ok
    end
  end
end