defmodule CartosnapApp.Photos do
@moduledoc """
Photos: uploading, editing, deleting, and seeing them.
Every function takes the caller's `%Scope{}` first. Changing a photo is
only ever its owner's; seeing one is its owner's, or anyone's who shares
a trip it's filed under (`get_viewable_photo!/2`). Trips themselves, and
filing photos under them, are `CartosnapApp.Trips`.
Changes are broadcast as `{:photo_created, photo}`, `{:photo_updated,
photo}` and `{:photo_deleted, photo}` on the owner's `"photos:<user id>"`
(see `subscribe/1`) and on the topic of every trip the photo is in
(`CartosnapApp.Trips.topic/1`), so open pages pick up thumbnails as the
image pipeline finishes them, whoever is looking.
"""
import Ecto.Query, warn: false
require Logger
alias CartosnapApp.Accounts.Scope
alias CartosnapApp.Photos.{Facets, Images, Photo, PhotoTrip}
alias CartosnapApp.Repo
alias CartosnapApp.Storage
alias CartosnapApp.Trips
alias CartosnapApp.Trips.Trip
alias CartosnapApp.Workers.ProcessImage
@facet_keys Facets.keys()
## Broadcasts
def subscribe(%Scope{user: user}),
do: Phoenix.PubSub.subscribe(CartosnapApp.PubSub, topic(user.id))
defp broadcast(%Photo{} = photo, event, trip_ids \\ nil) do
message = {event, photo}
Phoenix.PubSub.broadcast(CartosnapApp.PubSub, topic(photo.user), message)
for trip_id <- trip_ids || Trips.trip_ids_of(photo.id) do
Phoenix.PubSub.broadcast(CartosnapApp.PubSub, Trips.topic(trip_id), message)
end
:ok
end
defp topic(user_id), do: "photos:#{user_id}"
## Seeing photos
@doc """
The user's own photos, newest first.
Options:
* `:promoted` - only promoted photos when true
* `:trip_id` - only those filed under this trip
* `:mapped` - only photos with a position when true
* `:filters` - camera details to match, as `[{column, value}]` from
`CartosnapApp.Photos.Facets.from_params/1`
"""
def list_photos(%Scope{} = scope, opts \\ []) do
scope
|> photos_query(opts)
|> order_by([p], desc: p.date, desc: p.id)
|> Repo.all()
end
@doc "How many photos `list_photos/2` would return."
def count_photos(%Scope{} = scope, opts \\ []) do
scope |> photos_query(opts) |> Repo.aggregate(:count)
end
defp photos_query(%Scope{user: user}, opts) do
Enum.reduce(opts, from(p in Photo, where: p.user == ^user.id), fn
{:promoted, true}, q ->
where(q, [p], p.promoted == true)
{:mapped, true}, q ->
where(q, [p], not is_nil(p.geo_point))
{:filters, filters}, q ->
Enum.reduce(filters, q, fn {key, value}, q when key in @facet_keys ->
where(q, [p], field(p, ^key) == ^value)
end)
{:trip_id, trip_id}, q when is_binary(trip_id) ->
where(
q,
[p],
p.id in subquery(from pt in PhotoTrip, where: pt.trip == ^trip_id, select: pt.photo)
)
_, q ->
q
end)
end
@doc """
The values each camera detail takes among the photos `list_photos/2`
would return, with how many photos have each: `%{camera: [{"Apple
iPhone 15", 12}, ...], f_number: [{1.8, 9}, ...], ...}`.
Each facet is counted with every filter but its own applied, so a
chosen camera narrows the apertures on offer while the camera list still
shows the other cameras to switch to. Names come most-used first,
numbers in order.
"""
def facet_counts(%Scope{} = scope, opts \\ []) do
filters = Keyword.get(opts, :filters, [])
Map.new(Facets.all(), fn %{key: key, type: type} ->
others = Keyword.put(opts, :filters, Enum.reject(filters, &(elem(&1, 0) == key)))
order =
if type == :string,
do: [desc: dynamic([p], count(p.id)), asc: dynamic([p], field(p, ^key))],
else: [asc: dynamic([p], field(p, ^key))]
counts =
scope
|> photos_query(others)
|> where([p], not is_nil(field(p, ^key)))
|> group_by([p], field(p, ^key))
|> order_by(^order)
|> select([p], {field(p, ^key), count(p.id)})
|> Repo.all()
{key, counts}
end)
end
@doc "One of the user's own photos. Raises if it isn't theirs."
def get_photo!(%Scope{user: user}, id) do
Photo
|> where([p], p.id == ^id and p.user == ^user.id)
|> Repo.one!()
end
@doc """
A photo the user may look at: their own, or one filed under a trip they
own or belong to. Raises otherwise.
"""
def get_viewable_photo!(%Scope{user: user} = scope, id) do
photo = Repo.get!(Photo, id)
if photo.user == user.id or Trips.photo_trips(scope, photo) != [],
do: photo,
else: raise(Ecto.NoResultsError, queryable: Photo)
end
@doc """
The photos either side of `photo` in newest-first order:
`%{newer: photo | nil, older: photo | nil}`.
`within` is `:all` or `:promoted` (the user's own photos), or a trip the
user can see (everyone's photos in it).
"""
def neighbors(%Scope{} = scope, %Photo{} = photo, within \\ :all) do
base =
case within do
:all -> photos_query(scope, [])
:promoted -> photos_query(scope, promoted: true)
%Trip{} = trip -> Trips.album(trip)
end
newer =
base
|> where([p], p.date > ^photo.date or (p.date == ^photo.date and p.id > ^photo.id))
|> order_by([p], asc: p.date, asc: p.id)
|> limit(1)
|> Repo.one()
older =
base
|> where([p], p.date < ^photo.date or (p.date == ^photo.date and p.id < ^photo.id))
|> order_by([p], desc: p.date, desc: p.id)
|> limit(1)
|> Repo.one()
%{newer: newer, older: older}
end
## Uploading
@doc """
Takes in an uploaded file: stores the original, reads what it can from it
and queues the resizing. `entry` is a LiveView upload entry (or anything
with `:client_name` and `:client_type`).
With `trip_id:`, the photo is filed under that trip as well, in the same
transaction; the user must be able to see the trip.
With `client_ref:` (the id a device gave this upload), an upload already
made under that id is returned as it is, `{:ok, photo, :existing}`,
rather than stored again: a device retrying after a lost response gets
back the photo its first attempt made. Otherwise `{:ok, photo}`.
"""
def ingest_upload(%Scope{} = scope, path, %{client_name: _} = entry, opts \\ []) do
case opts[:client_ref] && get_photo_by_client_ref(scope, opts[:client_ref]) do
%Photo{} = existing -> {:ok, existing, :existing}
_ -> store_upload(scope, path, entry, opts)
end
end
@doc "The user's photo uploaded under a device's `client_ref`, or nil."
def get_photo_by_client_ref(%Scope{user: user}, client_ref) when is_binary(client_ref) do
Repo.get_by(Photo, user: user.id, client_ref: client_ref)
end
defp store_upload(%Scope{user: user} = scope, path, %{client_name: client_name} = entry, opts) do
trip = opts[:trip_id] && Trips.get_trip!(scope, opts[:trip_id])
ext = upload_ext(entry)
photo = %Photo{id: Ecto.UUID.generate(), user: user.id, client_ref: opts[:client_ref]}
key = Storage.key(photo, "orig", ext)
with :ok <- Storage.put(key, File.read!(path), Images.content_type(ext)) do
attrs =
path
|> Images.describe()
|> Map.merge(%{filename: client_name, url_original: key})
Ecto.Multi.new()
|> Ecto.Multi.insert(:photo, Photo.create_changeset(photo, attrs))
|> then(fn multi ->
if trip,
do: Ecto.Multi.insert(multi, :filed, %PhotoTrip{photo: photo.id, trip: trip.id}),
else: multi
end)
|> Oban.insert(:job, fn %{photo: photo} -> ProcessImage.new(%{id: photo.id}) end)
|> Repo.transaction()
|> case do
{:ok, %{photo: photo}} ->
broadcast(photo, :photo_created, if(trip, do: [trip.id], else: []))
{:ok, photo}
{:error, :photo, %Ecto.Changeset{errors: [client_ref: _]}, _} ->
# Another attempt with the same id won the race: theirs stands.
_ = Storage.delete(key)
{:ok, get_photo_by_client_ref(scope, opts[:client_ref]), :existing}
{:error, _step, reason, _} ->
{:error, reason}
end
end
end
defp upload_ext(%{client_type: type, client_name: name}) do
case type do
"image/jpeg" -> "jpg"
"image/png" -> "png"
"image/gif" -> "gif"
_ -> name |> Path.extname() |> String.trim_leading(".") |> String.downcase()
end
end
@doc "Records the variants the image pipeline made. Not scoped: the worker calls it."
def put_variants(%Photo{} = photo, attrs) do
with {:ok, photo} <- photo |> Photo.variants_changeset(attrs) |> Repo.update() do
broadcast(photo, :photo_updated)
{:ok, photo}
end
end
## Changing photos (their owner only)
def update_photo(%Scope{user: user}, %Photo{user: owner} = photo, attrs)
when owner == user.id do
with {:ok, photo} <- photo |> Photo.changeset(attrs) |> Repo.update() do
broadcast(photo, :photo_updated)
{:ok, photo}
end
end
@doc """
Places to offer when pinning `photo` by hand, so the same spot isn't
searched for again for every photo of a trip. From the photos of `trips`
(the ones it's in, which the viewer can see), or the owner's own photos
when it's in none:
* `:before` / `:after`: the nearest located photo taken just before and
just after it (a photo is most likely where the last one was);
* `:places`: the named places already used, most used first.
Each is `%{name, lat, lon}`; the neighbours also carry `:date`.
"""
def place_suggestions(%Scope{} = scope, %Photo{} = photo, trips, limit \\ 8) do
base = suggestion_base(scope, photo, trips)
%{
before: neighbour_place(base, photo, :before),
after: neighbour_place(base, photo, :after),
places: named_places(base, limit)
}
end
defp suggestion_base(_scope, photo, [_ | _] = trips) do
trip_ids = Enum.map(trips, & &1.id)
from p in Photo,
where: p.id != ^photo.id and not is_nil(p.geo_point),
where: p.id in subquery(from pt in PhotoTrip, where: pt.trip in ^trip_ids, select: pt.photo)
end
defp suggestion_base(%Scope{user: user}, photo, []) do
from p in Photo, where: p.id != ^photo.id and not is_nil(p.geo_point) and p.user == ^user.id
end
defp neighbour_place(_base, %Photo{date: nil}, _side), do: nil
defp neighbour_place(base, %Photo{date: date}, side) do
query =
case side do
:before -> from p in base, where: p.date <= ^date, order_by: [desc: p.date, desc: p.id]
:after -> from p in base, where: p.date >= ^date, order_by: [asc: p.date, asc: p.id]
end
case Repo.one(from p in query, limit: 1) do
nil ->
nil
neighbour ->
{lat, lon} = Photo.lat_lon(neighbour)
%{name: neighbour.place_name, lat: lat, lon: lon, date: neighbour.date}
end
end
# Where a name was used in more than one spot, the latest one.
defp named_places(base, limit) do
from(p in base,
where: not is_nil(p.place_name) and p.place_name != "",
group_by: p.place_name,
order_by: [desc: count(p.id), asc: p.place_name],
limit: ^limit,
select: %{
name: p.place_name,
lat: fragment("(array_agg(ST_Y(?) ORDER BY ? DESC NULLS LAST))[1]", p.geo_point, p.date),
lon: fragment("(array_agg(ST_X(?) ORDER BY ? DESC NULLS LAST))[1]", p.geo_point, p.date)
}
)
|> Repo.all()
end
@doc """
Pins a photo to `{lat, lon}` (labelled `place_name`, when picked from a
search), or unpins it with nil. Replaces whatever position it had,
including one from its GPS.
"""
def set_photo_location(scope, photo, position, place_name \\ nil)
def set_photo_location(%Scope{user: user}, %Photo{user: owner} = photo, position, place_name)
when owner == user.id do
with {:ok, photo} <- photo |> Photo.location_changeset(position, place_name) |> Repo.update() do
broadcast(photo, :photo_updated)
{:ok, photo}
end
end
def toggle_promoted(%Scope{} = scope, %Photo{} = photo),
do: update_photo(scope, photo, %{promoted: !photo.promoted})
def change_photo(%Photo{} = photo, attrs \\ %{}), do: Photo.changeset(photo, attrs)
@doc """
Deletes a photo and its files. A file that won't delete is logged and left
behind rather than keeping the photo.
"""
def delete_photo(%Scope{user: user}, %Photo{user: owner} = photo) when owner == user.id do
# Asked before the delete takes the photo's filings with it.
trip_ids = Trips.trip_ids_of(photo.id)
with {:ok, photo} <- Repo.delete(photo) do
for key <- [photo.url_original, photo.url_full, photo.url_preview, photo.url_thumb],
is_binary(key) do
case Storage.delete(key) do
:ok -> :ok
{:error, reason} -> Logger.warning("left #{key} in storage: #{inspect(reason)}")
end
end
broadcast(photo, :photo_deleted, trip_ids)
{:ok, photo}
end
end
## Many at once
@doc """
Promotes (true) or unpromotes (false) the user's photos among `ids`.
Others' ids are ignored. Returns how many changed.
"""
def set_promoted(%Scope{} = scope, ids, promoted?)
when is_list(ids) and is_boolean(promoted?) do
photos =
scope
|> photos_query([])
|> where([p], p.id in ^ids and p.promoted != ^promoted?)
|> Repo.all()
Enum.each(photos, fn photo ->
{:ok, _} = update_photo(scope, photo, %{promoted: promoted?})
end)
{:ok, length(photos)}
end
@doc "Deletes the user's photos among `ids`, with their files. Returns how many."
def delete_photos(%Scope{} = scope, ids) when is_list(ids) do
photos = scope |> photos_query([]) |> where([p], p.id in ^ids) |> Repo.all()
Enum.each(photos, fn photo -> {:ok, _} = delete_photo(scope, photo) end)
{:ok, length(photos)}
end
end
neiam
/cartosnap_ex
public · Issues · Pulls · Labels · Forks · Compare · Actions success · Badges · Packages
⭐
Log in to mark this repository.
13.6 KiB · text
History
1ba5ec3