12.2 KiB · text History 4d051ca
defmodule CartosnapApp.Photos do
  @moduledoc """
  The Photos context.
  """

  require Logger
  import Ecto.Query, warn: false
  alias CartosnapApp.Repo

  alias CartosnapApp.Photos.Trip

  import CartosnapApp.PostGISC
  import Geo.PostGIS

  @doc """
  Returns the list of photo_trips.

  ## Examples

      iex> list_photo_trips()
      [%Trip{}, ...]

  """
  def list_photo_trips do
    Repo.all(Trip)
  end

  def list_trip_ids(user) do
    q = from t in Trip,
    where: t.user == ^user,
    select: {t.name, t.id}
    Repo.all(q)
  end

  @doc """
  Gets a single trip.

  Raises `Ecto.NoResultsError` if the Trip does not exist.

  ## Examples

      iex> get_trip!(123)
      %Trip{}

      iex> get_trip!(456)
      ** (Ecto.NoResultsError)

  """
  def get_trip!(id), do: Repo.get!(Trip, id)

  @doc """
  Creates a trip.

  ## Examples

      iex> create_trip(%{field: value})
      {:ok, %Trip{}}

      iex> create_trip(%{field: bad_value})
      {:error, %Ecto.Changeset{}}

  """
  def create_trip(attrs \\ %{}) do
    %Trip{}
    |> Trip.changeset(attrs)
    |> Repo.insert()
  end

  @doc """
  Updates a trip.

  ## Examples

      iex> update_trip(trip, %{field: new_value})
      {:ok, %Trip{}}

      iex> update_trip(trip, %{field: bad_value})
      {:error, %Ecto.Changeset{}}

  """
  def update_trip(%Trip{} = trip, attrs) do
    trip
    |> Trip.changeset(attrs)
    |> Repo.update()
  end

  @doc """
  Deletes a trip.

  ## Examples

      iex> delete_trip(trip)
      {:ok, %Trip{}}

      iex> delete_trip(trip)
      {:error, %Ecto.Changeset{}}

  """
  def delete_trip(%Trip{} = trip) do
    Repo.delete(trip)
  end

  @doc """
  Returns an `%Ecto.Changeset{}` for tracking trip changes.

  ## Examples

      iex> change_trip(trip)
      %Ecto.Changeset{data: %Trip{}}

  """
  def change_trip(%Trip{} = trip, attrs \\ %{}) do
    Trip.changeset(trip, attrs)
  end

  alias CartosnapApp.Photos.Photo

  @doc """
  Returns the list of photo_photos.

  ## Examples

      iex> list_photo_photos()
      [%Photo{}, ...]

  """
  def list_photo_photos do
    Repo.all(Photo)
  end

  def list_photo_missing_minis do
    q = from p in Photo,
    where: is_nil(p.url_full) or is_nil(p.url_preview) or is_nil(p.url_thumb)
    Repo.all(q)
  end

  def list_photo_clusters_public(distance \\ 1.4) do
    q = from p in Photo,
             where: p.promoted == true,
             select: st_clusterwithin(p.geo_point, ^distance)
    Repo.all(q)
  end

  def list_photo_photos(user) do
    q = from p in Photo, where: p.user == ^user, order_by: [desc: p.date]
    Repo.all(q)
  end

  def list_photo_photos(user, :promoted) do
    q = from p in Photo, where: p.user == ^user and p.promoted == true, order_by: [desc: p.date]
    Repo.all(q)
  end

    def list_photo_photos(user, trip) do
    q = from p in Photo, where: p.user == ^user, order_by: [desc: p.date]
    Repo.all(q)
  end

  def list_photo_clusters(user, distance \\ 1.4) do
    q = from p in Photo,
             where: p.user == ^user,
             select: st_clusterwithin(p.geo_point, ^distance)
    Repo.all(q)
  end

  def list_photo_clusters_kmeans(user, qty \\ 3) do
    subq = from p in Photo,
                where: p.user == ^user and not is_nil(p.geo_point),
                select: %{
                  kmean: st_clusterkmeans(p.geo_point, ^qty),
                  geom: st_centroid(p.geo_point)
                }
    q = from e in subquery(subq),
             select: %{
               kmean: e.kmean,
               count: fragment("count(*)"),
               bbox: st_set_srid(st_extent(e.geom), 4326)
             },
             group_by: e.kmean
    Repo.all(q)
  end

  def list_photo_clusters_kmeans_obb(user, qty \\ 3) do
    subq = from p in Photo,
                where: p.user == ^user and not is_nil(p.geo_point),
                select: %{
                  kmean: st_clusterkmeans(p.geo_point, ^qty),
                  geom: st_centroid(p.geo_point)
                }
    q = from e in subquery(subq),
             select: %{
               kmean: e.kmean,
               count: fragment("count(*)"),
               bbox: st_set_srid(st_extent(e.geom), 4326)
             },
             group_by: e.kmean
    x = from f in subquery(q),
             select: %{
               bbox: st_set_srid(st_extent(f.bbox), 4326)
             }
   Repo.all(x)
  end


  @doc """
  Gets a single photo.

  Raises `Ecto.NoResultsError` if the Photo does not exist.

  ## Examples

      iex> get_photo!(123)
      %Photo{}

      iex> get_photo!(456)
      ** (Ecto.NoResultsError)

  """

  def get_photo(id), do: Repo.get(Photo, id)
  def get_photo!(id), do: Repo.get!(Photo, id)

  def get_photo(id, :trip)  do
    q = from p in Photo,
      left_join: pt in "photo_photo_trips",
      on: pt.photo == p.id,
      left_join: t in "photo_trips",
      on: pt.trip == t.id,
      select: %{p: p, trip_id: pt.trip, trip_name: t.name},
      where: p.id == ^id
    Repo.one(q)
  end

  def get_photo!(id, :trip)  do
    Repo.get!(Photo, id)
    q = from p in Photo,
      left_join: pt in "photo_photo_trips",
      on: pt.photo == p.id,
      left_join: t in "photo_trips",
      on: pt.trip == t.id,
      select: %{p: p, trip_id: pt.trip, trip_name: t.name},
      where: p.id == ^id,
      limit: 1
    Repo.one(q)
  end

  def get_next_photo(:photo, %Photo{} = ph) do
          q = from p in Photo,
          where: p.date > ^ph.date,
          order_by: [asc: p.date],
          limit: 1,
          left_join: pt in "photo_photo_trips",
          on: pt.photo == p.id,
          left_join: t in "photo_trips",
          on: pt.trip == t.id,
          select: %{p: p, trip_id: pt.trip, trip_name: t.name}
          q |> Repo.one
  end
  def get_next_photo(:trip, %Photo{} = ph, trip_id) do
    case trip_id do
      nil -> nil
      id -> q = from p in Photo,
          left_join: pt in "photo_photo_trips",
          on: pt.photo == p.id,
          left_join: t in "photo_trips",
          on: pt.trip == t.id,
          where: p.date > ^ph.date and p.promoted == true and pt.trip == ^trip_id,
          order_by: [asc: p.date],
          limit: 1,
          select: %{p: p, trip_id: pt.trip, trip_name: t.name}
          q |> Repo.one
    end
  end
4
  def get_next_photo(:promoted, %Photo{} = ph) do
          q = from p in Photo,
          where: p.date > ^ph.date and p.promoted == true,
          order_by: [asc: p.date],
          limit: 1,
          left_join: pt in "photo_photo_trips",
          on: pt.photo == p.id,
          left_join: t in "photo_trips",
          on: pt.trip == t.id,
          select: %{p: p, trip_id: pt.trip, trip_name: t.name}
          q |> Repo.one
  end

  def get_prev_photo(:photo, %Photo{} = ph) do
      q = from p in Photo,
          where: p.date < ^ph.date,
          order_by: [desc: p.date],
          limit: 1,
          left_join: pt in "photo_photo_trips",
          on: pt.photo == p.id,
          left_join: t in "photo_trips",
          on: pt.trip == t.id,
          select: %{p: p, trip_id: pt.trip, trip_name: t.name}
          q |> Repo.one
  end

  def get_prev_photo(:trip, %Photo{} = ph, trip_id) do
    case trip_id do
      nil -> nil
      id -> q = from p in Photo,
          left_join: pt in "photo_photo_trips",
          on: pt.photo == p.id,
          left_join: t in "photo_trips",
          on: pt.trip == t.id,
          where: p.date < ^ph.date and p.promoted == true and pt.trip == ^trip_id,
          order_by: [desc: p.date],
          limit: 1,
          select: %{p: p, trip_id: pt.trip, trip_name: t.name}
          q |> Repo.one
    end
  end

  def get_prev_photo(:promoted, %Photo{} = ph) do
      q = from p in Photo,
          where: p.date < ^ph.date and p.promoted == true,
          order_by: [desc: p.date],
          limit: 1,
          left_join: pt in "photo_photo_trips",
          on: pt.photo == p.id,
          left_join: t in "photo_trips",
          on: pt.trip == t.id,
          select: %{p: p, trip_id: pt.trip, trip_name: t.name}
          q |> Repo.one
  end

  @doc """
  Creates a photo.

  ## Examples

      iex> create_photo(%{field: value})
      {:ok, %Photo{}}

      iex> create_photo(%{field: bad_value})
      {:error, %Ecto.Changeset{}}

  """
  def create_photo_boot(attrs \\ %{}) do
    %Photo{}
    |> Photo.changeset_boot(attrs)
    |> Repo.insert()
  end

  def create_photo(attrs \\ %{}) do
    %Photo{}
    |> Photo.changeset(attrs)
    |> Repo.insert()
  end

  @doc """
  Updates a photo.

  ## Examples

      iex> update_photo(photo, %{field: new_value})
      {:ok, %Photo{}}

      iex> update_photo(photo, %{field: bad_value})
      {:error, %Ecto.Changeset{}}

  """
  def update_photo(%Photo{} = photo, attrs) do
    photo
    |> Photo.changeset(attrs)
    |> Repo.update()
  end

  def rename_photo(id, name) do
    get_photo(id) |> update_photo(%{name: name}) |> IO.inspect
  end

  @doc """
  Deletes a photo.

  ## Examples

      iex> delete_photo(photo)
      {:ok, %Photo{}}

      iex> delete_photo(photo)
      {:error, %Ecto.Changeset{}}

  """
  def delete_photo(%Photo{} = photo) do
    upload_cfg = Application.get_env(:cartosnap_app, :uploads)
    {:ok, auth} = B2Client.backend.authenticate(upload_cfg[:bucket_id], upload_cfg[:bucket_secret])
    {:ok, bucket} = B2Client.backend.get_bucket(auth, upload_cfg[:bucket])

    try do
      B2Client.backend.delete(auth, bucket, photo.url_original || "")
      B2Client.backend.delete(auth, bucket, photo.url_full || "")
      B2Client.backend.delete(auth, bucket, photo.url_preview || "")
      B2Client.backend.delete(auth, bucket, photo.url_thumb || "")
    rescue
      RuntimeError -> Logger.warn(":: Failed to delete images for #{photo.id} from backing store")
      # todo log this for future cleanup
    end

    Repo.delete(photo)
  end

  @doc """
  Returns an `%Ecto.Changeset{}` for tracking photo changes.

  ## Examples

      iex> change_photo(photo)
      %Ecto.Changeset{data: %Photo{}}

  """
  def change_photo(%Photo{} = photo, attrs \\ %{}) do
    Photo.changeset(photo, attrs)
  end

  alias CartosnapApp.Photos.PhotoTrip

  @doc """
  Returns the list of photo_photo_trips.

  ## Examples

      iex> list_photo_photo_trips()
      [%PhotoTrip{}, ...]

  """
  def list_photo_photo_trips do
    Repo.all(PhotoTrip)
  end

  @doc """
  Gets a single photo_trip.

  Raises `Ecto.NoResultsError` if the Photo trip does not exist.

  ## Examples

      iex> get_photo_trip!(123)
      %PhotoTrip{}

      iex> get_photo_trip!(456)
      ** (Ecto.NoResultsError)

  """
  def get_photo_trip!(id), do: Repo.get!(PhotoTrip, id)

  @doc """
  Creates a photo_trip.

  ## Examples

      iex> create_photo_trip(%{field: value})
      {:ok, %PhotoTrip{}}

      iex> create_photo_trip(%{field: bad_value})
      {:error, %Ecto.Changeset{}}

  """
  def create_photo_trip(attrs \\ %{}) do
    %PhotoTrip{}
    |> PhotoTrip.changeset(attrs)
    |> Repo.insert()
  end

  @doc """
  Updates a photo_trip.

  ## Examples

      iex> update_photo_trip(photo_trip, %{field: new_value})
      {:ok, %PhotoTrip{}}

      iex> update_photo_trip(photo_trip, %{field: bad_value})
      {:error, %Ecto.Changeset{}}

  """
  def update_photo_trip(%PhotoTrip{} = photo_trip, attrs) do
    photo_trip
    |> PhotoTrip.changeset(attrs)
    |> Repo.update()
  end

  @doc """
  Deletes a photo_trip.

  ## Examples

      iex> delete_photo_trip(photo_trip)
      {:ok, %PhotoTrip{}}

      iex> delete_photo_trip(photo_trip)
      {:error, %Ecto.Changeset{}}

  """
  def delete_photo_trip(%PhotoTrip{} = photo_trip) do
    Repo.delete(photo_trip)
  end

  @doc """
  Returns an `%Ecto.Changeset{}` for tracking photo_trip changes.

  ## Examples

      iex> change_photo_trip(photo_trip)
      %Ecto.Changeset{data: %PhotoTrip{}}

  """
  def change_photo_trip(%PhotoTrip{} = photo_trip, attrs \\ %{}) do
    PhotoTrip.changeset(photo_trip, attrs)
  end

  def set_photo_trip(photo_id, trip_id) do
#     clear_photo_trip(photo_id)
    create_photo_trip(%{photo: photo_id, trip: trip_id})
  end

  def clear_photo_trip(photo_id) do
    from(pt in PhotoTrip, where: pt.photo == ^photo_id) |> Repo.delete_all
  end

  def get_trip_random_photo(trip_id) do
    q = from pt in PhotoTrip,
        where: pt.trip == ^trip_id,
        left_join: p in "photo_photos",
        on: pt.photo == p.id,
        select: p.url_preview,
        limit: 1,
        order_by: fragment("RANDOM()")
    q |> Repo.one
  end
end