24.2 KiB · text History 44bc4f7
defmodule CartosnapApp.Trips do
  @moduledoc """
  Trips: shared albums of photos.

  A trip belongs to the user who made it (its owner). Anyone in it invites
  others, by address or by link; members see the trip and file their own
  photos under it, so the album is everyone's photos together. Only the
  owner renames, deletes, removes members or shares the trip by public link.

  Photos stay their uploader's: filing one under a trip lets the trip's
  people see it, nothing more. A photo may be in several trips.

  Album changes are broadcast on `topic/1` (`"trip:<id>"`): `:album_changed`
  when photos are filed or unfiled or members come and go, and the photo
  events from `CartosnapApp.Photos` for every photo in the trip.
  """

  import Ecto.Query, warn: false

  alias CartosnapApp.Accounts.{Scope, User}
  alias CartosnapApp.Photos.{Photo, PhotoTrip}
  alias CartosnapApp.Repo
  alias CartosnapApp.Trips.{Trip, TripInvite, TripMember, TripNotifier}

  ## Broadcasts

  def topic(%Trip{id: id}), do: topic(id)
  def topic(trip_id) when is_binary(trip_id), do: "trip:#{trip_id}"

  def subscribe(trip), do: Phoenix.PubSub.subscribe(CartosnapApp.PubSub, topic(trip))

  defp album_changed(trip_or_id),
    do: Phoenix.PubSub.broadcast(CartosnapApp.PubSub, topic(trip_or_id), :album_changed)

  ## Access

  # Trips the user owns or belongs to.
  defp accessible_query(%Scope{user: %{id: user_id}}) do
    members = from m in TripMember, where: m.user_id == ^user_id, select: m.trip_id
    from t in Trip, where: t.user == ^user_id or t.id in subquery(members)
  end

  @doc "Whether the user owns the trip."
  def owner?(%Scope{user: %{id: id}}, %Trip{user: owner}), do: id == owner
  def owner?(_scope, _trip), do: false

  @doc "Whether the user owns the trip or belongs to it."
  def member?(%Scope{} = scope, %Trip{} = trip) do
    owner?(scope, trip) or
      Repo.exists?(
        from m in TripMember, where: m.trip_id == ^trip.id and m.user_id == ^scope.user.id
      )
  end

  ## Trips

  @doc "Trips the user owns or belongs to, most recent first."
  def list_trips(%Scope{} = scope) do
    scope
    |> accessible_query()
    |> order_by([t], desc: t.date_start, asc: t.name)
    |> Repo.all()
  end

  @doc "A trip the user owns or belongs to. Raises otherwise."
  def get_trip!(%Scope{} = scope, id) do
    scope |> accessible_query() |> where([t], t.id == ^id) |> Repo.one!()
  end

  @doc "A trip the user owns or belongs to, as `{:ok, trip}`, or `:error`."
  def fetch_trip(%Scope{} = scope, id) do
    with {:ok, id} <- Ecto.UUID.cast(id),
         %Trip{} = trip <- scope |> accessible_query() |> where([t], t.id == ^id) |> Repo.one() do
      {:ok, trip}
    else
      _ -> :error
    end
  end

  @doc "The trips a user can file photos under, as `{name, id}` pairs for a select."
  def trip_options(%Scope{} = scope), do: scope |> list_trips() |> Enum.map(&{&1.name, &1.id})

  def create_trip(%Scope{user: user}, attrs) do
    %Trip{user: user.id}
    |> Trip.changeset(attrs)
    |> Repo.insert()
  end

  def update_trip(%Scope{user: user}, %Trip{user: owner} = trip, attrs) when owner == user.id do
    trip |> Trip.changeset(attrs) |> Repo.update()
  end

  def delete_trip(%Scope{user: user}, %Trip{user: owner} = trip) when owner == user.id do
    with {:ok, trip} <- Repo.delete(trip) do
      if trip.share_token, do: broadcast_share_revoked(trip)

      if trip.public do
        Phoenix.PubSub.broadcast(CartosnapApp.PubSub, public_topic(trip), :share_revoked)
        public_changed()
      end

      Phoenix.PubSub.broadcast(CartosnapApp.PubSub, topic(trip), :trip_deleted)
      {:ok, trip}
    end
  end

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

  ## The album

  defp album_query(trip_id) do
    from p in Photo,
      join: pt in PhotoTrip,
      on: pt.photo == p.id and pt.trip == ^trip_id
  end

  @doc """
  Everyone's photos in a trip, newest first. The caller must be able to see
  the trip (`get_trip!/2`). `promoted: true` narrows to promoted photos.
  """
  def list_album(%Trip{id: trip_id}, opts \\ []) do
    query = album_query(trip_id)
    query = if opts[:promoted], do: where(query, [p], p.promoted == true), else: query
    query |> order_by([p], desc: p.date, desc: p.id) |> Repo.all()
  end

  @doc "The query behind `list_album/2`, for stepping through a trip's photos."
  def album(%Trip{id: trip_id}), do: album_query(trip_id)

  @doc """
  For each of the given trips that has photos, a photo count and a cover (a
  random photo's preview): `%{trip_id => %{cover: key, count: n}}`.
  """
  def trip_summaries([]), do: %{}

  def trip_summaries(trips) do
    ids = Enum.map(trips, & &1.id)

    counts =
      from(pt in PhotoTrip,
        where: pt.trip in ^ids,
        group_by: pt.trip,
        select: {pt.trip, count(pt.id)}
      )
      |> Repo.all()
      |> Map.new()

    covers =
      from(pt in PhotoTrip,
        join: p in Photo,
        on: p.id == pt.photo,
        where: pt.trip in ^ids and not is_nil(p.url_preview),
        distinct: pt.trip,
        order_by: [pt.trip, fragment("random()")],
        select: {pt.trip, p.url_preview}
      )
      |> Repo.all()
      |> Map.new()

    Map.new(counts, fn {id, count} -> {id, %{count: count, cover: covers[id]}} end)
  end

  ## Filing

  @doc """
  Files the user's own photos (by id) under a trip they can see. Photos
  already in it, and ids that aren't theirs, are skipped. Returns how many
  were added.
  """
  def add_photos(%Scope{} = scope, trip_id, photo_ids) when is_list(photo_ids) do
    trip = get_trip!(scope, trip_id)
    now = NaiveDateTime.utc_now(:second)

    rows =
      from(p in Photo, where: p.id in ^photo_ids and p.user == ^scope.user.id, select: p.id)
      |> Repo.all()
      |> Enum.map(
        &%{id: Ecto.UUID.generate(), photo: &1, trip: trip.id, inserted_at: now, updated_at: now}
      )

    {count, _} =
      Repo.insert_all(PhotoTrip, rows, on_conflict: :nothing, conflict_target: [:photo, :trip])

    if count > 0, do: album_changed(trip)
    {:ok, count}
  end

  @doc """
  Takes a photo out of a trip. Its owner can, and so can the trip's owner,
  who looks after the album.
  """
  def remove_photo(%Scope{} = scope, %Trip{} = trip, %Photo{} = photo) do
    if photo.user == scope.user.id or owner?(scope, trip) do
      Repo.delete_all(from pt in PhotoTrip, where: pt.trip == ^trip.id and pt.photo == ^photo.id)
      album_changed(trip)
      :ok
    else
      {:error, :unauthorized}
    end
  end

  @doc "Which of the given trips (by id) a photo is in: the ones this user can see."
  def photo_trips(%Scope{} = scope, %Photo{id: photo_id}) do
    in_trip = from pt in PhotoTrip, where: pt.photo == ^photo_id, select: pt.trip

    scope
    |> accessible_query()
    |> where([t], t.id in subquery(in_trip))
    |> order_by([t], desc: t.date_start)
    |> Repo.all()
  end

  @doc "The ids of every trip a photo is in, whoever can see them: for broadcasts."
  def trip_ids_of(photo_id),
    do: Repo.all(from pt in PhotoTrip, where: pt.photo == ^photo_id, select: pt.trip)

  ## Members

  @doc "The trip's owner and members, owner first: `[%{user: user, owner?: bool}]`."
  def list_people(%Trip{} = trip) do
    owner = Repo.get!(User, trip.user)

    members =
      from(m in TripMember,
        join: u in assoc(m, :user),
        where: m.trip_id == ^trip.id,
        order_by: u.email,
        select: u
      )
      |> Repo.all()

    [%{user: owner, owner?: true} | Enum.map(members, &%{user: &1, owner?: false})]
  end

  @doc """
  The owner takes someone out of the trip, and their photos out of the
  album with them (the photos themselves are untouched).
  """
  def remove_member(%Scope{} = scope, %Trip{} = trip, user_id) do
    if owner?(scope, trip) and user_id != trip.user,
      do: drop_member(trip, user_id),
      else: {:error, :unauthorized}
  end

  @doc "A member leaves a trip, taking their photos out of its album."
  def leave_trip(%Scope{user: user} = scope, %Trip{} = trip) do
    if owner?(scope, trip), do: {:error, :owner_cannot_leave}, else: drop_member(trip, user.id)
  end

  defp drop_member(trip, user_id) do
    Repo.transact(fn ->
      Repo.delete_all(
        from m in TripMember, where: m.trip_id == ^trip.id and m.user_id == ^user_id
      )

      theirs = from p in Photo, where: p.user == ^user_id, select: p.id

      Repo.delete_all(
        from pt in PhotoTrip, where: pt.trip == ^trip.id and pt.photo in subquery(theirs)
      )

      {:ok, :ok}
    end)

    album_changed(trip)
    Phoenix.PubSub.broadcast(CartosnapApp.PubSub, topic(trip), {:member_removed, user_id})
    :ok
  end

  ## Invites
  #
  # Anyone in a trip can invite: by address (the invite is mailed, and waits
  # on the recipient's invites page) or as a bare link to hand over. Each
  # invite lets one person in and lasts a week; only its hash is kept, so
  # its link exists in the mail, or on the inviter's screen once, and
  # nowhere else. The owner can take back any invite, the rest their own.

  @doc """
  Invites someone to the trip. `email` nil makes a link-only invite.
  `url_fun` turns the raw token into the invite's URL, for the mail.

  Returns `{:ok, invite}` with the raw token in `invite.token`, or
  `{:error, reason}`: `:unauthorized` (not in the trip), `:already_member`
  or `:already_invited` (that address), or an invalid changeset.
  """
  def create_invite(%Scope{user: user} = scope, %Trip{} = trip, email \\ nil, url_fun \\ nil) do
    email = TripInvite.normalize_email(email)

    cond do
      not member?(scope, trip) -> {:error, :unauthorized}
      email && email_in_trip?(trip, email) -> {:error, :already_member}
      email && email_invited?(trip, email) -> {:error, :already_invited}
      true -> insert_invite(TripInvite.build(trip.id, user.id, email), user, trip, url_fun)
    end
  end

  defp insert_invite(changeset, inviter, trip, url_fun) do
    with {:ok, invite} <- Repo.insert(changeset) do
      mail_invite(invite, inviter, trip, url_fun)
      {:ok, invite}
    end
  end

  defp mail_invite(%TripInvite{email: nil}, _inviter, _trip, _url_fun), do: :ok
  defp mail_invite(_invite, _inviter, _trip, nil), do: :ok

  defp mail_invite(%TripInvite{email: email, token: token}, inviter, trip, url_fun) do
    TripNotifier.deliver_invite(
      email,
      CartosnapApp.Accounts.display_name(inviter),
      trip,
      url_fun.(token)
    )
  end

  defp email_in_trip?(trip, email) do
    owner = from u in User, where: u.id == ^trip.user, select: u.email

    members =
      from m in TripMember,
        join: u in assoc(m, :user),
        where: m.trip_id == ^trip.id,
        select: u.email

    Repo.exists?(
      from u in subquery(union_all(owner, ^members)),
        where: fragment("lower(?)", u.email) == ^email
    )
  end

  defp email_invited?(trip, email) do
    now = DateTime.utc_now(:second)

    Repo.exists?(
      from i in TripInvite,
        where:
          i.trip_id == ^trip.id and i.email == ^email and is_nil(i.used_at) and
            i.expires_at > ^now
    )
  end

  @doc "The trip's invites not yet used or expired, newest first, with who made them."
  def list_pending_invites(%Trip{id: trip_id}) do
    now = DateTime.utc_now(:second)

    Repo.all(
      from i in TripInvite,
        where: i.trip_id == ^trip_id and is_nil(i.used_at) and i.expires_at > ^now,
        order_by: [desc: i.inserted_at],
        preload: :created_by
    )
  end

  @doc "Whether this user may take back (or resend) the invite: the trip's owner, or whoever made it."
  def manages_invite?(%Scope{user: user} = scope, %Trip{} = trip, %TripInvite{} = invite),
    do: owner?(scope, trip) or invite.created_by_id == user.id

  @doc "Takes back an unused invite."
  def revoke_invite(%Scope{} = scope, %Trip{} = trip, invite_id) do
    with %TripInvite{} = invite <- Repo.get_by(TripInvite, id: invite_id, trip_id: trip.id),
         true <- manages_invite?(scope, trip, invite) do
      Repo.delete!(invite)
      :ok
    else
      _ -> {:error, :unauthorized}
    end
  end

  @doc """
  Sends an addressed invite again, with a new link and a fresh week (the
  old link stops working).
  """
  def resend_invite(%Scope{user: user} = scope, %Trip{} = trip, invite_id, url_fun) do
    with %TripInvite{email: email} = invite when is_binary(email) <-
           Repo.get_by(TripInvite, id: invite_id, trip_id: trip.id),
         true <- manages_invite?(scope, trip, invite),
         {:ok, invite} <- invite |> TripInvite.renew_changeset() |> Repo.update() do
      mail_invite(invite, user, trip, url_fun)
      {:ok, invite}
    else
      _ -> {:error, :unauthorized}
    end
  end

  @doc """
  People this user might want in the trip: everyone they share another trip
  with, and everyone they've invited by address before, less anyone already
  in this trip or invited to it. `[%{email: email, user: user | nil}]`,
  people with accounts first.
  """
  def suggested_invitees(%Scope{user: user} = scope, %Trip{} = trip) do
    my_trips = scope |> accessible_query() |> where([t], t.id != ^trip.id) |> select([t], t.id)

    fellow_ids =
      Repo.all(from m in TripMember, where: m.trip_id in subquery(my_trips), select: m.user_id) ++
        Repo.all(from t in Trip, where: t.id in subquery(my_trips), select: t.user)

    fellows =
      Repo.all(from u in User, where: u.id in ^Enum.uniq(fellow_ids) and u.id != ^user.id)
      |> Enum.map(&%{email: String.downcase(&1.email), user: &1})

    invited =
      Repo.all(
        from i in TripInvite,
          where: i.created_by_id == ^user.id and not is_nil(i.email),
          distinct: i.email,
          select: i.email
      )
      |> Enum.map(&%{email: &1, user: nil})

    (fellows ++ invited)
    |> Enum.uniq_by(& &1.email)
    |> Enum.reject(&(email_in_trip?(trip, &1.email) or email_invited?(trip, &1.email)))
    |> Enum.sort_by(&{is_nil(&1.user), &1.email})
  end

  @doc """
  The invite a link's token names, with its trip and inviter: `{:ok,
  invite}`, or `{:error, :not_found | :expired | :used}`.
  """
  def get_invite(token) when is_binary(token) and byte_size(token) >= 32 do
    case Repo.get_by(TripInvite, token_hash: TripInvite.hash(token)) do
      nil -> {:error, :not_found}
      invite -> check_invite(Repo.preload(invite, [:trip, :created_by]))
    end
  end

  def get_invite(_token), do: {:error, :not_found}

  defp check_invite(invite) do
    cond do
      TripInvite.used?(invite) -> {:error, :used}
      TripInvite.expired?(invite) -> {:error, :expired}
      true -> {:ok, invite}
    end
  end

  @doc """
  Joins the user to the invite's trip and uses the invite up. Someone
  already in the trip joins nothing and leaves the invite for whoever it
  was meant for. Returns `{:ok, trip}`.
  """
  def accept_invite(%Scope{} = scope, token) do
    with {:ok, invite} <- get_invite(token), do: use_invite(scope, invite)
  end

  @doc """
  Accepts, from the invites page, an invite addressed to this user's own
  (confirmed) address: no link needed, the address is the proof.
  """
  def accept_invite_for_me(%Scope{user: user} = scope, invite_id) do
    case Enum.find(list_my_invites(scope), &(&1.id == invite_id)) do
      nil -> {:error, :not_found}
      invite -> use_invite(scope, %{invite | email: String.downcase(user.email)})
    end
  end

  defp use_invite(%Scope{user: user} = scope, invite) do
    trip = invite.trip

    if member?(scope, trip) do
      {:ok, trip}
    else
      Repo.transact(fn ->
        Repo.insert!(%TripMember{trip_id: trip.id, user_id: user.id},
          on_conflict: :nothing,
          conflict_target: [:trip_id, :user_id]
        )

        Repo.update!(TripInvite.use_changeset(invite, user.id))
        {:ok, trip}
      end)
      |> tap(fn _ -> album_changed(trip) end)
    end
  end

  @doc """
  Unused invites addressed to this user's address, newest first, with their
  trips and inviters: what their invites page lists. Only for a confirmed
  address, since it is the address that lets them in.
  """
  def list_my_invites(%Scope{user: %User{confirmed_at: nil}}), do: []

  def list_my_invites(%Scope{user: user} = scope) do
    now = DateTime.utc_now(:second)
    email = String.downcase(user.email)
    mine = scope |> accessible_query() |> select([t], t.id)

    Repo.all(
      from i in TripInvite,
        where:
          i.email == ^email and is_nil(i.used_at) and i.expires_at > ^now and
            i.trip_id not in subquery(mine),
        order_by: [desc: i.inserted_at],
        preload: [:trip, :created_by]
    )
    |> Enum.uniq_by(& &1.trip_id)
  end

  @doc """
  Joins a trip from an addressed invite without an account yet: makes a
  confirmed account for the address it was sent to and joins it to the
  trip, `{:ok, user, trip}`. The link stands in for a confirmation mail:
  whoever holds a link addressed to someone has what a mailed link would
  have given them.

  Refuses `:not_addressed` (a link invite proves no address) and
  `:has_account`: an invite must never sign anyone in to an existing
  account, or inviting someone's address would hand it over. They log in.
  """
  def join_by_invite(token) do
    with {:ok, invite} <- get_invite(token),
         {:addressed, email} when is_binary(email) <- {:addressed, invite.email},
         nil <- CartosnapApp.Accounts.get_user_by_email(email),
         {:ok, user} <- CartosnapApp.Accounts.register_confirmed_user(email),
         {:ok, trip} <- use_invite(Scope.for_user(user), invite) do
      {:ok, user, trip}
    else
      {:addressed, nil} -> {:error, :not_addressed}
      %User{} -> {:error, :has_account}
      error -> error
    end
  end

  ## Sharing by public link

  @doc """
  Shares a trip by link, making its token if it has none; owner only.
  Sharing an already-shared trip keeps its link.
  """
  def share_trip(%Scope{} = scope, %Trip{share_token: nil} = trip),
    do: put_share_token(scope, trip)

  def share_trip(%Scope{user: user}, %Trip{user: owner} = trip) when owner == user.id,
    do: {:ok, trip}

  @doc """
  Replaces a trip's share link: the old one stops working, and anyone
  viewing through it is sent away.
  """
  def rotate_share_link(%Scope{} = scope, %Trip{} = trip) do
    with {:ok, updated} <- put_share_token(scope, trip) do
      broadcast_share_revoked(trip)
      {:ok, updated}
    end
  end

  @doc "Stops sharing a trip by link; anyone viewing through the link is sent away."
  def stop_sharing(%Scope{user: user}, %Trip{user: owner} = trip) when owner == user.id do
    with {:ok, updated} <- trip |> Ecto.Changeset.change(share_token: nil) |> Repo.update() do
      broadcast_share_revoked(trip)
      {:ok, updated}
    end
  end

  ## Public

  @doc """
  Opens the trip to anyone (true): listed on the front page and viewable at
  `/t/<id>`, no link needed. False closes it again, and anyone viewing it
  publicly is sent away. Owner only, and independent of sharing by link.
  """
  def set_public(%Scope{user: user}, %Trip{user: owner} = trip, public?)
      when owner == user.id and is_boolean(public?) do
    # Forced: a struct read before another tab changed it would otherwise
    # look unchanged and write nothing.
    changeset = trip |> Ecto.Changeset.change() |> Ecto.Changeset.force_change(:public, public?)

    with {:ok, updated} <- Repo.update(changeset) do
      unless public?,
        do: Phoenix.PubSub.broadcast(CartosnapApp.PubSub, public_topic(trip), :share_revoked)

      public_changed()
      {:ok, updated}
    end
  end

  @doc "Whether the public see only the trip's promoted photos."
  def set_public_promoted_only(%Scope{user: user}, %Trip{user: owner} = trip, value)
      when owner == user.id and is_boolean(value) do
    with {:ok, updated} <-
           trip |> Trip.share_changeset(%{public_promoted_only: value}) |> Repo.update() do
      Phoenix.PubSub.broadcast(CartosnapApp.PubSub, public_topic(trip), :share_changed)
      public_changed()
      {:ok, updated}
    end
  end

  @doc """
  Turns splitting the album into areas (`CartosnapApp.Trips.Areas`) on or
  off. The owner's to change; everyone in the trip sees it, as
  `{:areas_changed, on?}` on the trip's topic.
  """
  def set_areas(%Scope{user: user}, %Trip{user: owner} = trip, on?)
      when owner == user.id and is_boolean(on?) do
    with {:ok, updated} <- trip |> Trip.areas_changeset(%{areas: on?}) |> Repo.update() do
      Phoenix.PubSub.broadcast(CartosnapApp.PubSub, topic(trip), {:areas_changed, on?})
      {:ok, updated}
    end
  end

  @doc "A public trip by id, or nil: for anyone, signed in or not."
  def get_public_trip(id) do
    case Ecto.UUID.cast(id) do
      {:ok, id} -> Repo.get_by(Trip, id: id, public: true)
      :error -> nil
    end
  end

  @doc "What the public see of a trip: its photos oldest first, promoted only if so set."
  def list_public_photos(%Trip{} = trip) do
    query = trip.id |> album_query() |> order_by([p], asc: p.date, asc: p.id)
    query = if trip.public_promoted_only, do: where(query, [p], p.promoted == true), else: query
    Repo.all(query)
  end

  @doc """
  The PubSub topic (and Presence room) of a trip's public viewers: apart
  from `share_topic/1`, so strangers never see who the link was sent to.
  """
  def public_topic(%Trip{id: id}), do: "public:#{id}"

  @doc "Listens for trips opening to or closing from the public: `:public_trips_changed`."
  def subscribe_public, do: Phoenix.PubSub.subscribe(CartosnapApp.PubSub, "trips:public")

  defp public_changed,
    do: Phoenix.PubSub.broadcast(CartosnapApp.PubSub, "trips:public", :public_trips_changed)

  @doc """
  The public trips, most recent first, each with its owner's name, what the
  public see of it and a cover: `[%{trip: trip, owner: name, count: n,
  cover: key, photos: photos}]`. Trips that show nothing (promoted only,
  with none promoted) are left out.
  """
  def list_public_trips do
    trips = Repo.all(from t in Trip, where: t.public, order_by: [desc: t.date_start, asc: t.name])
    names = trips |> Enum.map(& &1.user) |> CartosnapApp.Accounts.display_names()
    photos = public_photos_by_trip(trips)

    for trip <- trips, shown = Map.get(photos, trip.id, []), shown != [] do
      cover = Enum.find_value(shown, & &1.url_preview)
      %{trip: trip, owner: names[trip.user], count: length(shown), cover: cover, photos: shown}
    end
  end

  # Each public trip's photos as the public see them, newest first; capped,
  # since this is everyone's front page.
  @public_photo_cap 2_000

  defp public_photos_by_trip([]), do: %{}

  defp public_photos_by_trip(trips) do
    promoted_only = for t <- trips, t.public_promoted_only, do: t.id
    ids = Enum.map(trips, & &1.id)

    from(p in Photo,
      join: pt in PhotoTrip,
      on: pt.photo == p.id,
      where: pt.trip in ^ids,
      where: p.promoted or pt.trip not in ^promoted_only,
      order_by: [desc: p.date],
      limit: @public_photo_cap,
      select: {pt.trip, p}
    )
    |> Repo.all()
    |> Enum.group_by(&elem(&1, 0), &elem(&1, 1))
  end

  @doc "Whether the shared view shows only the trip's promoted photos."
  def set_share_promoted_only(%Scope{user: user}, %Trip{user: owner} = trip, value)
      when owner == user.id and is_boolean(value) do
    with {:ok, updated} <-
           trip |> Trip.share_changeset(%{share_promoted_only: value}) |> Repo.update() do
      Phoenix.PubSub.broadcast(CartosnapApp.PubSub, share_topic(trip), :share_changed)
      {:ok, updated}
    end
  end

  defp put_share_token(%Scope{user: user}, %Trip{user: owner} = trip) when owner == user.id do
    token = 32 |> :crypto.strong_rand_bytes() |> Base.url_encode64(padding: false)
    trip |> Ecto.Changeset.change(share_token: token) |> Repo.update()
  end

  defp broadcast_share_revoked(%Trip{} = trip),
    do: Phoenix.PubSub.broadcast(CartosnapApp.PubSub, share_topic(trip), :share_revoked)

  @doc """
  The PubSub topic a shared trip's viewers listen on (and are tracked in by
  `CartosnapAppWeb.Presence`).
  """
  def share_topic(%Trip{id: id}), do: "share:#{id}"

  @doc """
  The trip a share token opens, or nil. Deliberately not scoped: holding the
  token is the permission.
  """
  def get_shared_trip(token) when is_binary(token) and byte_size(token) >= 32 do
    Repo.get_by(Trip, share_token: token)
  end

  def get_shared_trip(_token), do: nil

  @doc """
  What a shared trip shows: everyone's photos in it, in the order they were
  taken (promoted ones only if the owner said so).
  """
  def list_shared_photos(%Trip{} = trip) do
    query = trip.id |> album_query() |> order_by([p], asc: p.date, asc: p.id)
    query = if trip.share_promoted_only, do: where(query, [p], p.promoted == true), else: query
    Repo.all(query)
  end
end