From c6e6a6100028af8b3b276636ed01579221a6c84b Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Mon, 3 Dec 2018 12:29:31 +0100 Subject: [PATCH] Event changeset more cleaner Signed-off-by: Thomas Citharel --- lib/mobilizon/actors/actor.ex | 9 +++++++ lib/mobilizon/events/event.ex | 45 ++++++++++++++++++++++------------- 2 files changed, 37 insertions(+), 17 deletions(-) diff --git a/lib/mobilizon/actors/actor.ex b/lib/mobilizon/actors/actor.ex index 39b802add..0d3e33767 100644 --- a/lib/mobilizon/actors/actor.ex +++ b/lib/mobilizon/actors/actor.ex @@ -322,4 +322,13 @@ defmodule Mobilizon.Actors.Actor do |> Enum.map(& &1.actor_id) |> Enum.member?(follower_actor_id) end + + @spec actor_acct_from_actor(struct()) :: String.t() + def actor_acct_from_actor(%Actor{preferred_username: preferred_username, domain: domain}) do + if is_nil(domain) do + preferred_username + else + "#{preferred_username}@#{domain}" + end + end end diff --git a/lib/mobilizon/events/event.ex b/lib/mobilizon/events/event.ex index 10ee6fb03..5f76d6e50 100644 --- a/lib/mobilizon/events/event.ex +++ b/lib/mobilizon/events/event.ex @@ -45,21 +45,6 @@ defmodule Mobilizon.Events.Event do @doc false def changeset(%Event{} = event, attrs) do - # TODO : Change all of this - actor_url = - if Map.has_key?(attrs, :organizer_actor) do - attrs.organizer_actor.preferred_username - else - "" - end - - uuid = Ecto.UUID.generate() - - url = - if Map.has_key?(attrs, "url"), - do: attrs["url"], - else: "#{MobilizonWeb.Endpoint.url()}/@#{actor_url}/#{uuid}" - event |> Ecto.Changeset.cast(attrs, [ :title, @@ -81,8 +66,7 @@ defmodule Mobilizon.Events.Event do ]) |> cast_assoc(:tags) |> cast_assoc(:physical_address) - |> put_change(:uuid, uuid) - |> put_change(:url, url) + |> build_url() |> validate_required([ :title, :begins_on, @@ -93,4 +77,31 @@ defmodule Mobilizon.Events.Event do :address_type ]) end + + @spec build_url(Ecto.Changeset.t()) :: Ecto.Changeset.t() + defp build_url(%Ecto.Changeset{changes: %{url: _url}} = changeset), do: changeset + + defp build_url(%Ecto.Changeset{changes: %{organizer_actor: organizer_actor}} = changeset) do + organizer_actor + |> Actor.actor_acct_from_actor() + |> do_build_url(changeset) + end + + defp build_url(%Ecto.Changeset{changes: %{organizer_actor_id: organizer_actor_id}} = changeset) do + organizer_actor_id + |> Mobilizon.Actors.get_actor!() + |> Actor.actor_acct_from_actor() + |> do_build_url(changeset) + end + + defp build_url(%Ecto.Changeset{} = changeset), do: changeset + + @spec do_build_url(String.t(), Ecto.Changeset.t()) :: Ecto.Changeset.t() + defp do_build_url(actor_acct, changeset) do + uuid = Ecto.UUID.generate() + + changeset + |> put_change(:uuid, uuid) + |> put_change(:url, "#{MobilizonWeb.Endpoint.url()}/@#{actor_acct}/#{uuid}") + end end