5.2 KiB · text History 44bc4f7
defmodule CartosnapApp.Photos.Photo do
  @moduledoc """
  One photo. The original lives in storage under `url_original`; the image
  pipeline (`CartosnapApp.Workers.ProcessImage`) fills in the `url_full`,
  `url_preview` and `url_thumb` variants afterwards. The `url_*` fields hold
  storage keys, not URLs: `CartosnapApp.Storage.public_url/1` makes them
  fetchable.

  `geo_point` is where it was taken, read from the EXIF GPS block. It is a
  PostGIS point in the usual order, `x = longitude, y = latitude` (SRID
  4326); build one with `point/2` and read it with `lat_lon/1` rather than
  unpacking the tuple by hand. A position set by hand (`location_changeset/3`)
  carries the `place_name` it was picked from; one from GPS has none.
  """

  use Ecto.Schema
  import Ecto.Changeset

  @primary_key {:id, :binary_id, autogenerate: true}
  @foreign_key_type :binary_id
  schema "photo_photos" do
    field :blurhash, :string
    field :date, :utc_datetime
    field :exif, :map
    field :filename, :string
    field :geo_point, Geo.PostGIS.Geometry
    field :name, :string
    field :place_name, :string
    # Camera details, from EXIF (see CartosnapApp.Photos.Facets).
    field :camera, :string
    field :lens, :string
    field :f_number, :float
    field :focal_length, :float
    field :iso, :integer
    field :exposure, :float
    # As displayed, and the photo's shape: nil, "sphere" or "panorama"
    # (CartosnapApp.Photos.Panorama). Filled in by the image pipeline.
    field :width, :integer
    field :height, :integer
    field :kind, :string
    field :pano, :map
    field :promoted, :boolean, default: false
    field :url_full, :string
    field :url_original, :string
    field :url_preview, :string
    field :url_thumb, :string
    field :user, :binary_id
    # The id a device gave its upload (`Photos.ingest_upload/4`); set by the
    # context, never cast.
    field :client_ref, :string

    many_to_many :trips, CartosnapApp.Trips.Trip,
      join_through: "photo_photo_trips",
      join_keys: [photo: :id, trip: :id]

    timestamps()
  end

  @doc """
  A freshly uploaded photo. `id` and `user` are set on the struct by the
  caller, never cast.
  """
  def create_changeset(photo, attrs) do
    photo
    |> cast(attrs, [
      :name,
      :exif,
      :filename,
      :date,
      :url_original,
      :blurhash,
      :geo_point | CartosnapApp.Photos.Facets.keys()
    ])
    |> validate_required([:id, :user, :filename, :date, :url_original])
    |> unique_constraint(:client_ref, name: :photo_photos_user_client_ref_index)
  end

  @doc "What a person may change about their photo."
  def changeset(photo, attrs) do
    photo
    |> cast(attrs, [:name, :promoted])
    |> update_change(:name, &blank_to_nil/1)
    |> validate_length(:name, max: 200)
  end

  @doc """
  Pins the photo to `{lat, lon}`, or takes its position away with nil.
  `place_name` is what it was picked as, if it was picked from a search.
  """
  def location_changeset(photo, nil, _place_name) do
    change(photo, geo_point: nil, place_name: nil)
  end

  def location_changeset(photo, {lat, lon}, place_name) do
    photo
    |> change(place_name: place_name)
    |> validate_length(:place_name, max: 255)
    |> put_point(lat, lon)
  end

  defp put_point(changeset, lat, lon)
       when is_number(lat) and is_number(lon) and lat >= -90 and lat <= 90 and lon >= -180 and
              lon <= 180 do
    put_change(changeset, :geo_point, point(lat, lon))
  end

  defp put_point(changeset, _lat, _lon),
    do: add_error(changeset, :geo_point, "is not a position on Earth")

  @doc "The resized variants, written by the image pipeline."
  def variants_changeset(photo, attrs) do
    photo
    |> cast(attrs, [:url_full, :url_preview, :url_thumb, :width, :height, :kind, :pano])
    |> validate_required([:url_full, :url_preview, :url_thumb])
  end

  @doc "Whether it's a photo sphere, seen in the 360° viewer."
  def sphere?(%__MODULE__{kind: "sphere", pano: %{}}), do: true
  def sphere?(_photo), do: false

  @doc "Whether it's a wide panorama, panned across."
  def panorama?(%__MODULE__{kind: "panorama"}), do: true
  def panorama?(_photo), do: false

  @doc "Whether the pipeline has finished with this photo."
  def processed?(%__MODULE__{url_thumb: thumb}), do: not is_nil(thumb)

  @doc "Where the photo was taken, as `{lat, lon}`, or nil."
  def lat_lon(%__MODULE__{geo_point: %Geo.Point{coordinates: {lon, lat}}})
      when is_number(lat) and is_number(lon),
      do: {lat, lon}

  def lat_lon(_), do: nil

  @doc "The stored point for a position: `x = lon, y = lat`, as PostGIS expects."
  def point(lat, lon), do: %Geo.Point{coordinates: {lon, lat}, srid: 4326}

  @doc "The name to show: the photo's own, or its file name."
  def title(%__MODULE__{name: name}) when is_binary(name) and name != "", do: name
  def title(%__MODULE__{filename: filename}), do: filename

  @doc "The file extension of the original, lowercase, without the dot."
  def ext(%__MODULE__{url_original: key}) when is_binary(key),
    do: key |> Path.extname() |> String.trim_leading(".") |> String.downcase()

  defp blank_to_nil(value) when is_binary(value) do
    case String.trim(value) do
      "" -> nil
      trimmed -> trimmed
    end
  end

  defp blank_to_nil(value), do: value
end