Various refactoring and typespec improvements

Signed-off-by: Thomas Citharel <tcit@tcit.fr>
This commit is contained in:
Thomas Citharel 2021-09-24 16:46:42 +02:00
parent d235653876
commit 1893d9f55b
No known key found for this signature in database
GPG Key ID: A061B9DDE0CA0773
142 changed files with 1854 additions and 1297 deletions

View File

@ -75,7 +75,7 @@ defmodule Mobilizon.Federation.ActivityPub do
""" """
# TODO: Make database calls parallel # TODO: Make database calls parallel
@spec fetch_object_from_url(String.t(), Keyword.t()) :: @spec fetch_object_from_url(String.t(), Keyword.t()) ::
{:ok, struct()} | {:error, any()} {:ok, struct()} | {:ok, atom(), struct()} | {:error, any()}
def fetch_object_from_url(url, options \\ []) do def fetch_object_from_url(url, options \\ []) do
Logger.info("Fetching object from url #{url}") Logger.info("Fetching object from url #{url}")
@ -111,7 +111,7 @@ defmodule Mobilizon.Federation.ActivityPub do
@spec handle_existing_entity(String.t(), struct(), Keyword.t()) :: @spec handle_existing_entity(String.t(), struct(), Keyword.t()) ::
{:ok, struct()} {:ok, struct()}
| {:ok, struct()} | {:ok, atom(), struct()}
| {:error, String.t(), struct()} | {:error, String.t(), struct()}
| {:error, String.t()} | {:error, String.t()}
defp handle_existing_entity(url, entity, options) do defp handle_existing_entity(url, entity, options) do
@ -126,13 +126,13 @@ defmodule Mobilizon.Federation.ActivityPub do
{:ok, entity} = Preloader.maybe_preload(entity) {:ok, entity} = Preloader.maybe_preload(entity)
{:error, status, entity} {:error, status, entity}
err -> {:error, err} ->
err {:error, err}
end end
end end
@spec refresh_entity(String.t(), struct(), Keyword.t()) :: @spec refresh_entity(String.t(), struct(), Keyword.t()) ::
{:ok, struct()} | {:error, String.t(), struct()} | {:error, String.t()} {:ok, struct()} | {:error, atom(), struct()} | {:error, String.t()}
defp refresh_entity(url, entity, options) do defp refresh_entity(url, entity, options) do
force_fetch = Keyword.get(options, :force, false) force_fetch = Keyword.get(options, :force, false)
@ -205,21 +205,22 @@ defmodule Mobilizon.Federation.ActivityPub do
* Returns the activity * Returns the activity
""" """
@spec update(Entity.entities(), map(), boolean, map()) :: @spec update(Entity.entities(), map(), boolean, map()) ::
{:ok, Activity.t(), Entity.entities()} | any() {:ok, Activity.t(), Entity.entities()} | {:error, any()}
def update(old_entity, args, local \\ false, additional \\ %{}) do def update(old_entity, args, local \\ false, additional \\ %{}) do
Logger.debug("updating an activity") Logger.debug("updating an activity")
Logger.debug(inspect(args)) Logger.debug(inspect(args))
with {:ok, entity, update_data} <- Managable.update(old_entity, args, additional), case Managable.update(old_entity, args, additional) do
{:ok, activity} <- create_activity(update_data, local), {:ok, entity, update_data} ->
:ok <- maybe_federate(activity), {:ok, activity} = create_activity(update_data, local)
:ok <- maybe_relay_if_group_activity(activity) do maybe_federate(activity)
maybe_relay_if_group_activity(activity)
{:ok, activity, entity} {:ok, activity, entity}
else
err -> {:error, err} ->
Logger.error("Something went wrong while creating an activity") Logger.error("Something went wrong while creating an activity")
Logger.debug(inspect(err)) Logger.debug(inspect(err))
err {:error, err}
end end
end end
@ -274,7 +275,7 @@ defmodule Mobilizon.Federation.ActivityPub do
end end
@spec announce(Actor.t(), ActivityStream.t(), String.t() | nil, boolean, boolean) :: @spec announce(Actor.t(), ActivityStream.t(), String.t() | nil, boolean, boolean) ::
{:ok, Activity.t(), ActivityStream.t()} {:ok, Activity.t(), ActivityStream.t()} | {:error, any()}
def announce( def announce(
%Actor{} = actor, %Actor{} = actor,
object, object,
@ -318,7 +319,7 @@ defmodule Mobilizon.Federation.ActivityPub do
Make an actor follow another Make an actor follow another
""" """
@spec follow(Actor.t(), Actor.t(), String.t() | nil, boolean, map) :: @spec follow(Actor.t(), Actor.t(), String.t() | nil, boolean, map) ::
{:ok, Activity.t(), Follower.t()} | {:error, String.t()} {:ok, Activity.t(), Follower.t()} | {:error, atom | Ecto.Changeset.t() | String.t()}
def follow( def follow(
%Actor{} = follower, %Actor{} = follower,
%Actor{} = followed, %Actor{} = followed,
@ -326,22 +327,22 @@ defmodule Mobilizon.Federation.ActivityPub do
local \\ true, local \\ true,
additional \\ %{} additional \\ %{}
) do ) do
with {:different_actors, true} <- {:different_actors, followed.id != follower.id}, if followed.id != follower.id do
{:ok, activity_data, %Follower{} = follower} <- case Types.Actors.follow(
Types.Actors.follow(
follower, follower,
followed, followed,
local, local,
Map.merge(additional, %{"activity_id" => activity_id}) Map.merge(additional, %{"activity_id" => activity_id})
), ) do
{:ok, activity} <- create_activity(activity_data, local), {:ok, activity_data, %Follower{} = follower} ->
:ok <- maybe_federate(activity) do {:ok, activity} = create_activity(activity_data, local)
maybe_federate(activity)
{:ok, activity, follower} {:ok, activity, follower}
else
{:error, err, msg} when err in [:already_following, :suspended, :no_person] ->
{:error, msg}
{:different_actors, _} -> {:error, err} ->
{:error, err}
end
else
{:error, "Can't follow yourself"} {:error, "Can't follow yourself"}
end end
end end
@ -350,7 +351,7 @@ defmodule Mobilizon.Federation.ActivityPub do
Make an actor unfollow another Make an actor unfollow another
""" """
@spec unfollow(Actor.t(), Actor.t(), String.t() | nil, boolean()) :: @spec unfollow(Actor.t(), Actor.t(), String.t() | nil, boolean()) ::
{:ok, Activity.t(), Follower.t()} {:ok, Activity.t(), Follower.t()} | {:error, String.t()}
def unfollow(%Actor{} = follower, %Actor{} = followed, activity_id \\ nil, local \\ true) do def unfollow(%Actor{} = follower, %Actor{} = followed, activity_id \\ nil, local \\ true) do
with {:ok, %Follower{id: follow_id} = follow} <- Actors.unfollow(followed, follower), with {:ok, %Follower{id: follow_id} = follow} <- Actors.unfollow(followed, follower),
# We recreate the follow activity # We recreate the follow activity
@ -385,18 +386,19 @@ defmodule Mobilizon.Federation.ActivityPub do
end end
@spec join(Event.t(), Actor.t(), boolean, map) :: @spec join(Event.t(), Actor.t(), boolean, map) ::
{:ok, Activity.t(), Participant.t()} | {:maximum_attendee_capacity, any} {:ok, Activity.t(), Participant.t()} | {:error, :maximum_attendee_capacity}
@spec join(Actor.t(), Actor.t(), boolean, map) :: {:ok, Activity.t(), Member.t()} @spec join(Actor.t(), Actor.t(), boolean, map) :: {:ok, Activity.t(), Member.t()}
def join(entity_to_join, actor_joining, local \\ true, additional \\ %{}) def join(entity_to_join, actor_joining, local \\ true, additional \\ %{})
def join(%Event{} = event, %Actor{} = actor, local, additional) do def join(%Event{} = event, %Actor{} = actor, local, additional) do
with {:ok, activity_data, participant} <- Types.Events.join(event, actor, local, additional), case Types.Events.join(event, actor, local, additional) do
{:ok, activity} <- create_activity(activity_data, local), {:ok, activity_data, participant} ->
:ok <- maybe_federate(activity) do {:ok, activity} = create_activity(activity_data, local)
maybe_federate(activity)
{:ok, activity, participant} {:ok, activity, participant}
else
{:maximum_attendee_capacity, err} -> {:error, :maximum_attendee_capacity_reached} ->
{:maximum_attendee_capacity, err} {:error, :maximum_attendee_capacity_reached}
{:accept, accept} -> {:accept, accept} ->
accept accept
@ -415,7 +417,9 @@ defmodule Mobilizon.Federation.ActivityPub do
end end
end end
@spec leave(Event.t(), Actor.t(), boolean, map) :: {:ok, Activity.t(), Participant.t()} @spec leave(Event.t(), Actor.t(), boolean, map) ::
{:ok, Activity.t(), Participant.t()}
| {:error, :is_only_organizer | :participant_not_found | Ecto.Changeset.t()}
@spec leave(Actor.t(), Actor.t(), boolean, map) :: {:ok, Activity.t(), Member.t()} @spec leave(Actor.t(), Actor.t(), boolean, map) :: {:ok, Activity.t(), Member.t()}
def leave(object, actor, local \\ true, additional \\ %{}) def leave(object, actor, local \\ true, additional \\ %{})
@ -428,28 +432,37 @@ defmodule Mobilizon.Federation.ActivityPub do
local, local,
additional additional
) do ) do
with {:only_organizer, false} <- if Participant.is_not_only_organizer(event_id, actor_id) do
{:only_organizer, Participant.is_not_only_organizer(event_id, actor_id)}, {:error, :is_only_organizer}
{:ok, %Participant{} = participant} <- else
Mobilizon.Events.get_participant( case Mobilizon.Events.get_participant(
event_id, event_id,
actor_id, actor_id,
Map.get(additional, :metadata, %{}) Map.get(additional, :metadata, %{})
), ) do
{:ok, %Participant{} = participant} <- {:ok, %Participant{} = participant} ->
Events.delete_participant(participant), case Events.delete_participant(participant) do
leave_data <- %{ {:ok, %{participant: %Participant{} = participant}} ->
leave_data = %{
"type" => "Leave", "type" => "Leave",
# If it's an exclusion it should be something else # If it's an exclusion it should be something else
"actor" => actor_url, "actor" => actor_url,
"object" => event_url, "object" => event_url,
"id" => "#{Endpoint.url()}/leave/event/#{participant.id}" "id" => "#{Endpoint.url()}/leave/event/#{participant.id}"
}, }
audience <-
Audience.get_audience(participant), audience = Audience.get_audience(participant)
{:ok, activity} <- create_activity(Map.merge(leave_data, audience), local), {:ok, activity} = create_activity(Map.merge(leave_data, audience), local)
:ok <- maybe_federate(activity) do maybe_federate(activity)
{:ok, activity, participant} {:ok, activity, participant}
{:error, _type, %Ecto.Changeset{} = err, _} ->
{:error, err}
end
{:error, :participant_not_found} ->
{:error, :participant_not_found}
end
end end
end end

View File

@ -24,22 +24,17 @@ defmodule Mobilizon.Federation.ActivityPub.Actor do
def get_or_fetch_actor_by_url(nil, _preload), do: {:error, :url_nil} def get_or_fetch_actor_by_url(nil, _preload), do: {:error, :url_nil}
def get_or_fetch_actor_by_url("https://www.w3.org/ns/activitystreams#Public", _preload) do def get_or_fetch_actor_by_url("https://www.w3.org/ns/activitystreams#Public", _preload) do
case Relay.get_actor() do %Actor{url: url} = Relay.get_actor()
%Actor{url: url} ->
get_or_fetch_actor_by_url(url) get_or_fetch_actor_by_url(url)
{:error, %Ecto.Changeset{}} ->
{:error, :no_internal_relay_actor}
end
end end
def get_or_fetch_actor_by_url(url, preload) do def get_or_fetch_actor_by_url(url, preload) do
case Actors.get_actor_by_url(url, preload) do case Actors.get_actor_by_url(url, preload) do
{:ok, %Actor{} = cached_actor} -> {:ok, %Actor{} = cached_actor} ->
unless Actors.needs_update?(cached_actor) do if Actors.needs_update?(cached_actor) do
{:ok, cached_actor}
else
__MODULE__.make_actor_from_url(url, preload) __MODULE__.make_actor_from_url(url, preload)
else
{:ok, cached_actor}
end end
{:error, :actor_not_found} -> {:error, :actor_not_found} ->

View File

@ -12,8 +12,8 @@ defmodule Mobilizon.Federation.ActivityPub.Federator do
alias Mobilizon.Actors.Actor alias Mobilizon.Actors.Actor
alias Mobilizon.Federation.ActivityPub alias Mobilizon.Federation.ActivityPub
alias Mobilizon.Federation.ActivityPub.{Activity, Transmogrifier}
alias Mobilizon.Federation.ActivityPub.Actor, as: ActivityPubActor alias Mobilizon.Federation.ActivityPub.Actor, as: ActivityPubActor
alias Mobilizon.Federation.ActivityPub.Transmogrifier
require Logger require Logger
@ -58,9 +58,6 @@ defmodule Mobilizon.Federation.ActivityPub.Federator do
{:ok, activity, _data} -> {:ok, activity, _data} ->
{:ok, activity} {:ok, activity}
%Activity{} ->
Logger.info("Already had #{params["id"]}")
e -> e ->
# Just drop those for now # Just drop those for now
Logger.debug("Unhandled activity") Logger.debug("Unhandled activity")

View File

@ -20,7 +20,6 @@ defmodule Mobilizon.Federation.ActivityPub.Fetcher do
@spec fetch(String.t(), Keyword.t()) :: @spec fetch(String.t(), Keyword.t()) ::
{:ok, map()} {:ok, map()}
| {:ok, Tesla.Env.t()} | {:ok, Tesla.Env.t()}
| {:error, String.t()}
| {:error, any()} | {:error, any()}
| {:error, :invalid_url} | {:error, :invalid_url}
def fetch(url, options \\ []) do def fetch(url, options \\ []) do
@ -109,7 +108,8 @@ defmodule Mobilizon.Federation.ActivityPub.Fetcher do
end end
end end
@type fetch_actor_errors :: :json_decode_error | :actor_deleted | :http_error @type fetch_actor_errors ::
:json_decode_error | :actor_deleted | :http_error | :actor_not_allowed_type
@doc """ @doc """
Fetching a remote actor's information through its AP ID Fetching a remote actor's information through its AP ID
@ -130,7 +130,14 @@ defmodule Mobilizon.Federation.ActivityPub.Fetcher do
case Jason.decode(body) do case Jason.decode(body) do
{:ok, data} when is_map(data) -> {:ok, data} when is_map(data) ->
Logger.debug("Got activity+json response at actor's endpoint, now converting data") Logger.debug("Got activity+json response at actor's endpoint, now converting data")
{:ok, ActorConverter.as_to_model_data(data)}
case ActorConverter.as_to_model_data(data) do
{:error, :actor_not_allowed_type} ->
{:error, :actor_not_allowed_type}
map when is_map(map) ->
{:ok, map}
end
{:error, %Jason.DecodeError{} = e} -> {:error, %Jason.DecodeError{} = e} ->
Logger.warn("Could not decode actor at fetch #{url}, #{inspect(e)}") Logger.warn("Could not decode actor at fetch #{url}, #{inspect(e)}")
@ -164,12 +171,7 @@ defmodule Mobilizon.Federation.ActivityPub.Fetcher do
@spec address_valid?(String.t()) :: boolean @spec address_valid?(String.t()) :: boolean
defp address_valid?(address) do defp address_valid?(address) do
case URI.parse(address) do %URI{host: host, scheme: scheme} = URI.parse(address)
%URI{host: host, scheme: scheme} ->
is_valid_string(host) and is_valid_string(scheme) is_valid_string(host) and is_valid_string(scheme)
_ ->
false
end
end end
end end

View File

@ -26,21 +26,25 @@ defmodule Mobilizon.Federation.ActivityPub.Refresher do
Relay.get_actor() Relay.get_actor()
end end
with :ok <- fetch_group(url, on_behalf_of) do case fetch_group(url, on_behalf_of) do
{:error, error} ->
{:error, error}
:ok ->
{:ok, group} {:ok, group}
end end
end end
def refresh_profile(%Actor{type: type, url: url}) when type in [:Person, :Application] do def refresh_profile(%Actor{type: type, url: url}) when type in [:Person, :Application] do
case ActivityPubActor.make_actor_from_url(url) do case ActivityPubActor.make_actor_from_url(url) do
{:error, error} ->
{:error, error}
{:ok, %Actor{outbox_url: outbox_url} = actor} -> {:ok, %Actor{outbox_url: outbox_url} = actor} ->
case fetch_collection(outbox_url, Relay.get_actor()) do case fetch_collection(outbox_url, Relay.get_actor()) do
:ok -> {:ok, actor} :ok -> {:ok, actor}
{:error, error} -> {:error, error} {:error, error} -> {:error, error}
end end
{:error, error} ->
{:error, error}
end end
end end
@ -49,6 +53,11 @@ defmodule Mobilizon.Federation.ActivityPub.Refresher do
@spec fetch_group(String.t(), Actor.t()) :: :ok | {:error, fetch_actor_errors} @spec fetch_group(String.t(), Actor.t()) :: :ok | {:error, fetch_actor_errors}
def fetch_group(group_url, %Actor{} = on_behalf_of) do def fetch_group(group_url, %Actor{} = on_behalf_of) do
case ActivityPubActor.make_actor_from_url(group_url) do case ActivityPubActor.make_actor_from_url(group_url) do
{:error, err}
when err in [:actor_deleted, :http_error, :json_decode_error, :actor_is_local] ->
Logger.debug("Error while making actor")
{:error, err}
{:ok, {:ok,
%Actor{ %Actor{
outbox_url: outbox_url, outbox_url: outbox_url,
@ -75,11 +84,6 @@ defmodule Mobilizon.Federation.ActivityPub.Refresher do
Logger.debug("Error while fetching actor collection") Logger.debug("Error while fetching actor collection")
{:error, err} {:error, err}
end end
{:error, err}
when err in [:actor_deleted, :http_error, :json_decode_error, :actor_is_local] ->
Logger.debug("Error while making actor")
{:error, err}
end end
end end
@ -113,7 +117,7 @@ defmodule Mobilizon.Federation.ActivityPub.Refresher do
end end
end end
@spec fetch_element(String.t(), Actor.t()) :: any() @spec fetch_element(String.t(), Actor.t()) :: {:ok, struct()} | {:error, any()}
def fetch_element(url, %Actor{} = on_behalf_of) do def fetch_element(url, %Actor{} = on_behalf_of) do
with {:ok, data} <- Fetcher.fetch(url, on_behalf_of: on_behalf_of) do with {:ok, data} <- Fetcher.fetch(url, on_behalf_of: on_behalf_of) do
case handling_element(data) do case handling_element(data) do
@ -123,6 +127,9 @@ defmodule Mobilizon.Federation.ActivityPub.Refresher do
{:ok, entity} -> {:ok, entity} ->
{:ok, entity} {:ok, entity}
:error ->
{:error, :err_fetching_element}
err -> err ->
{:error, err} {:error, err}
end end

View File

@ -27,76 +27,100 @@ defmodule Mobilizon.Federation.ActivityPub.Relay do
get_actor() get_actor()
end end
@spec get_actor() :: Actor.t() | {:error, Ecto.Changeset.t()} @spec get_actor() :: Actor.t() | no_return
def get_actor do def get_actor do
with {:ok, %Actor{} = actor} <- case Actors.get_or_create_internal_actor("relay") do
Actors.get_or_create_internal_actor("relay") do {:ok, %Actor{} = actor} ->
actor actor
{:error, %Ecto.Changeset{} = _err} ->
raise("Relay actor not found")
end end
end end
@spec follow(String.t()) :: {:ok, Activity.t(), Follower.t()} @spec follow(String.t()) ::
{:ok, Activity.t(), Follower.t()} | {:error, atom()} | {:error, String.t()}
def follow(address) do def follow(address) do
%Actor{} = local_actor = get_actor()
with {:ok, target_instance} <- fetch_actor(address), with {:ok, target_instance} <- fetch_actor(address),
%Actor{} = local_actor <- get_actor(),
{:ok, %Actor{} = target_actor} <- {:ok, %Actor{} = target_actor} <-
ActivityPubActor.get_or_fetch_actor_by_url(target_instance), ActivityPubActor.get_or_fetch_actor_by_url(target_instance),
{:ok, activity, follow} <- Follows.follow(local_actor, target_actor) do {:ok, activity, follow} <- Follows.follow(local_actor, target_actor) do
Logger.info("Relay: followed instance #{target_instance}; id=#{activity.data["id"]}") Logger.info("Relay: followed instance #{target_instance}; id=#{activity.data["id"]}")
{:ok, activity, follow} {:ok, activity, follow}
else else
{:error, :person_no_follow} ->
Logger.warn("Only group and instances can be followed")
{:error, :person_no_follow}
{:error, e} -> {:error, e} ->
Logger.warn("Error while following remote instance: #{inspect(e)}") Logger.warn("Error while following remote instance: #{inspect(e)}")
{:error, e} {:error, e}
e ->
Logger.warn("Error while following remote instance: #{inspect(e)}")
{:error, e}
end end
end end
@spec unfollow(String.t()) :: {:ok, Activity.t(), Follower.t()} @spec unfollow(String.t()) ::
{:ok, Activity.t(), Follower.t()} | {:error, atom()} | {:error, String.t()}
def unfollow(address) do def unfollow(address) do
%Actor{} = local_actor = get_actor()
with {:ok, target_instance} <- fetch_actor(address), with {:ok, target_instance} <- fetch_actor(address),
%Actor{} = local_actor <- get_actor(),
{:ok, %Actor{} = target_actor} <- {:ok, %Actor{} = target_actor} <-
ActivityPubActor.get_or_fetch_actor_by_url(target_instance), ActivityPubActor.get_or_fetch_actor_by_url(target_instance),
{:ok, activity, follow} <- Follows.unfollow(local_actor, target_actor) do {:ok, activity, follow} <- Follows.unfollow(local_actor, target_actor) do
Logger.info("Relay: unfollowed instance #{target_instance}: id=#{activity.data["id"]}") Logger.info("Relay: unfollowed instance #{target_instance}: id=#{activity.data["id"]}")
{:ok, activity, follow} {:ok, activity, follow}
else else
e -> {:error, e} ->
Logger.warn("Error while unfollowing remote instance: #{inspect(e)}") Logger.warn("Error while unfollowing remote instance: #{inspect(e)}")
{:error, e} {:error, e}
end end
end end
@spec accept(String.t()) :: {:ok, Activity.t(), Follower.t()} @spec accept(String.t()) ::
{:ok, Activity.t(), Follower.t()} | {:error, atom()} | {:error, String.t()}
def accept(address) do def accept(address) do
Logger.debug("We're trying to accept a relay subscription") Logger.debug("We're trying to accept a relay subscription")
%Actor{} = local_actor = get_actor()
with {:ok, target_instance} <- fetch_actor(address), with {:ok, target_instance} <- fetch_actor(address),
%Actor{} = local_actor <- get_actor(),
{:ok, %Actor{} = target_actor} <- {:ok, %Actor{} = target_actor} <-
ActivityPubActor.get_or_fetch_actor_by_url(target_instance), ActivityPubActor.get_or_fetch_actor_by_url(target_instance),
{:ok, activity, follow} <- Follows.accept(target_actor, local_actor) do {:ok, activity, follow} <- Follows.accept(target_actor, local_actor) do
{:ok, activity, follow} {:ok, activity, follow}
else
{:error, e} ->
Logger.warn("Error while accepting remote instance follow: #{inspect(e)}")
{:error, e}
end end
end end
@spec reject(String.t()) ::
{:ok, Activity.t(), Follower.t()} | {:error, atom()} | {:error, String.t()}
def reject(address) do def reject(address) do
Logger.debug("We're trying to reject a relay subscription") Logger.debug("We're trying to reject a relay subscription")
%Actor{} = local_actor = get_actor()
with {:ok, target_instance} <- fetch_actor(address), with {:ok, target_instance} <- fetch_actor(address),
%Actor{} = local_actor <- get_actor(),
{:ok, %Actor{} = target_actor} <- {:ok, %Actor{} = target_actor} <-
ActivityPubActor.get_or_fetch_actor_by_url(target_instance), ActivityPubActor.get_or_fetch_actor_by_url(target_instance),
{:ok, activity, follow} <- Follows.reject(target_actor, local_actor) do {:ok, activity, follow} <- Follows.reject(target_actor, local_actor) do
{:ok, activity, follow} {:ok, activity, follow}
else
{:error, e} ->
Logger.warn("Error while rejecting remote instance follow: #{inspect(e)}")
{:error, e}
end end
end end
@spec refresh(String.t()) :: {:ok, any()} @spec refresh(String.t()) ::
{:ok, Oban.Job.t()}
| {:error, Ecto.Changeset.t()}
| {:error, :bad_url}
| {:error, Mobilizon.Federation.ActivityPub.Actor.make_actor_errors()}
| {:error, :no_internal_relay_actor}
| {:error, :url_nil}
def refresh(address) do def refresh(address) do
Logger.debug("We're trying to refresh a remote instance") Logger.debug("We're trying to refresh a remote instance")
@ -106,6 +130,10 @@ defmodule Mobilizon.Federation.ActivityPub.Relay do
Background.enqueue("refresh_profile", %{ Background.enqueue("refresh_profile", %{
"actor_id" => target_actor_id "actor_id" => target_actor_id
}) })
else
{:error, e} ->
Logger.warn("Error while refreshing remote instance: #{inspect(e)}")
{:error, e}
end end
end end

View File

@ -87,7 +87,7 @@ defmodule Mobilizon.Federation.ActivityPub.Transmogrifier do
{:existing_comment, {:ok, %Comment{} = comment}} -> {:existing_comment, {:ok, %Comment{} = comment}} ->
{:ok, nil, comment} {:ok, nil, comment}
{:error, :event_comments_are_closed} -> {:error, :event_not_allow_commenting} ->
Logger.debug("Tried to reply to an event for which comments are closed") Logger.debug("Tried to reply to an event for which comments are closed")
:error :error
end end
@ -210,7 +210,11 @@ defmodule Mobilizon.Federation.ActivityPub.Transmogrifier do
{:ok, activity, object} <- ActivityPub.follow(follower, followed, id, false) do {:ok, activity, object} <- ActivityPub.follow(follower, followed, id, false) do
{:ok, activity, object} {:ok, activity, object}
else else
e -> {:error, :person_no_follow} ->
Logger.warn("Only group and instances can be followed")
:error
{:error, e} ->
Logger.warn("Unable to handle Follow activity #{inspect(e)}") Logger.warn("Unable to handle Follow activity #{inspect(e)}")
:error :error
end end
@ -578,6 +582,8 @@ defmodule Mobilizon.Federation.ActivityPub.Transmogrifier do
def handle_incoming( def handle_incoming(
%{"type" => "Delete", "object" => object, "actor" => _actor, "id" => _id} = data %{"type" => "Delete", "object" => object, "actor" => _actor, "id" => _id} = data
) do ) do
Logger.info("Handle incoming to delete an object")
with actor_url <- Utils.get_actor(data), with actor_url <- Utils.get_actor(data),
{:actor, {:ok, %Actor{} = actor}} <- {:actor, {:ok, %Actor{} = actor}} <-
{:actor, ActivityPubActor.get_or_fetch_actor_by_url(actor_url)}, {:actor, ActivityPubActor.get_or_fetch_actor_by_url(actor_url)},
@ -594,7 +600,7 @@ defmodule Mobilizon.Federation.ActivityPub.Transmogrifier do
Logger.warn("Object origin check failed") Logger.warn("Object origin check failed")
:error :error
{:actor, {:error, "Could not fetch by AP id"}} -> {:actor, {:error, _err}} ->
{:error, :unknown_actor} {:error, :unknown_actor}
{:error, e} -> {:error, e} ->
@ -993,7 +999,6 @@ defmodule Mobilizon.Federation.ActivityPub.Transmogrifier do
end end
# Comment initiates a whole discussion only if it has full title # Comment initiates a whole discussion only if it has full title
@spec is_data_for_comment_or_discussion?(map()) :: boolean()
defp is_data_a_discussion_initialization?(object_data) do defp is_data_a_discussion_initialization?(object_data) do
not Map.has_key?(object_data, :title) or not Map.has_key?(object_data, :title) or
is_nil(object_data.title) or object_data.title == "" is_nil(object_data.title) or object_data.title == ""
@ -1107,22 +1112,22 @@ defmodule Mobilizon.Federation.ActivityPub.Transmogrifier do
end end
defp is_group_object_gone(object_id) do defp is_group_object_gone(object_id) do
case ActivityPub.fetch_object_from_url(object_id, force: true) do Logger.debug("is_group_object_gone #{object_id}")
{:error, error_message, object} when error_message in [:http_gone, :http_not_found] ->
{:ok, object}
case ActivityPub.fetch_object_from_url(object_id, force: true) do
# comments are just emptied # comments are just emptied
{:ok, %Comment{deleted_at: deleted_at} = object} when not is_nil(deleted_at) -> {:ok, %Comment{deleted_at: deleted_at} = object} when not is_nil(deleted_at) ->
{:ok, object} {:ok, object}
{:error, :http_gone, object} ->
Logger.debug("object is really gone")
{:ok, object}
{:ok, %{url: url} = object} -> {:ok, %{url: url} = object} ->
if Utils.are_same_origin?(url, Endpoint.url()), if Utils.are_same_origin?(url, Endpoint.url()),
do: {:ok, object}, do: {:ok, object},
else: {:error, "Group object URL remote"} else: {:error, "Group object URL remote"}
{:error, {:error, err}} ->
{:error, err}
{:error, err} -> {:error, err} ->
{:error, err} {:error, err}

View File

@ -18,40 +18,49 @@ defmodule Mobilizon.Federation.ActivityPub.Types.Actors do
@behaviour Entity @behaviour Entity
@impl Entity @impl Entity
@spec create(map(), map()) :: {:ok, Actor.t(), ActivityStream.t()} @spec create(map(), map()) ::
{:ok, Actor.t(), ActivityStream.t()} | {:error, Ecto.Changeset.t()}
def create(args, additional) do def create(args, additional) do
with args <- prepare_args_for_actor(args), args = prepare_args_for_actor(args)
{:ok, %Actor{} = actor} <- Actors.create_actor(args),
{:ok, _} <- case Actors.create_actor(args) do
{:ok, %Actor{} = actor} ->
GroupActivity.insert_activity(actor, GroupActivity.insert_activity(actor,
subject: "group_created", subject: "group_created",
actor_id: args.creator_actor_id actor_id: args.creator_actor_id
), )
actor_as_data <- Convertible.model_to_as(actor),
audience <- %{"to" => ["https://www.w3.org/ns/activitystreams#Public"], "cc" => []}, actor_as_data = Convertible.model_to_as(actor)
create_data <- audience = %{"to" => ["https://www.w3.org/ns/activitystreams#Public"], "cc" => []}
make_create_data(actor_as_data, Map.merge(audience, additional)) do create_data = make_create_data(actor_as_data, Map.merge(audience, additional))
{:ok, actor, create_data} {:ok, actor, create_data}
{:error, %Ecto.Changeset{} = err} ->
{:error, err}
end end
end end
@impl Entity @impl Entity
@spec update(Actor.t(), map, map) :: {:ok, Actor.t(), ActivityStream.t()} @spec update(Actor.t(), map, map) ::
{:ok, Actor.t(), ActivityStream.t()} | {:error, Ecto.Changeset.t()}
def update(%Actor{} = old_actor, args, additional) do def update(%Actor{} = old_actor, args, additional) do
with {:ok, %Actor{} = new_actor} <- Actors.update_actor(old_actor, args), case Actors.update_actor(old_actor, args) do
{:ok, _} <- {:ok, %Actor{} = new_actor} ->
GroupActivity.insert_activity(new_actor, GroupActivity.insert_activity(new_actor,
subject: "group_updated", subject: "group_updated",
old_group: old_actor, old_group: old_actor,
updater_actor: Map.get(args, :updater_actor) updater_actor: Map.get(args, :updater_actor)
), )
actor_as_data <- Convertible.model_to_as(new_actor),
{:ok, true} <- Cachex.del(:activity_pub, "actor_#{new_actor.preferred_username}"), actor_as_data = Convertible.model_to_as(new_actor)
audience <- Cachex.del(:activity_pub, "actor_#{new_actor.preferred_username}")
Audience.get_audience(new_actor), audience = Audience.get_audience(new_actor)
additional <- Map.merge(additional, %{"actor" => old_actor.url}), additional = Map.merge(additional, %{"actor" => old_actor.url})
update_data <- make_update_data(actor_as_data, Map.merge(audience, additional)) do update_data = make_update_data(actor_as_data, Map.merge(audience, additional))
{:ok, new_actor, update_data} {:ok, new_actor, update_data}
{:error, %Ecto.Changeset{} = err} ->
{:error, err}
end end
end end
@ -92,21 +101,24 @@ defmodule Mobilizon.Federation.ActivityPub.Types.Actors do
suspension = Map.get(additionnal, :suspension, false) suspension = Map.get(additionnal, :suspension, false)
with {:ok, %Oban.Job{}} <- case Actors.delete_actor(target_actor,
Actors.delete_actor(target_actor,
# We completely delete the actor if the actor is remote # We completely delete the actor if the actor is remote
reserve_username: is_nil(domain), reserve_username: is_nil(domain),
suspension: suspension, suspension: suspension,
author_id: author_id author_id: author_id
) do ) do
{:ok, %Oban.Job{}} ->
{:ok, activity_data, actor, target_actor} {:ok, activity_data, actor, target_actor}
{:error, %Ecto.Changeset{} = err} ->
{:error, err}
end end
end end
@spec actor(Actor.t()) :: Actor.t() | nil @spec actor(Actor.t()) :: Actor.t() | nil
def actor(%Actor{} = actor), do: actor def actor(%Actor{} = actor), do: actor
@spec actor(Actor.t()) :: Actor.t() | nil @spec group_actor(Actor.t()) :: Actor.t() | nil
def group_actor(%Actor{} = actor), do: actor def group_actor(%Actor{} = actor), do: actor
@spec permissions(Actor.t()) :: Permission.t() @spec permissions(Actor.t()) :: Permission.t()
@ -121,12 +133,12 @@ defmodule Mobilizon.Federation.ActivityPub.Types.Actors do
@spec join(Actor.t(), Actor.t(), boolean(), map()) :: {:ok, ActivityStreams.t(), Member.t()} @spec join(Actor.t(), Actor.t(), boolean(), map()) :: {:ok, ActivityStreams.t(), Member.t()}
def join(%Actor{type: :Group} = group, %Actor{} = actor, _local, additional) do def join(%Actor{type: :Group} = group, %Actor{} = actor, _local, additional) do
with role <- role =
additional additional
|> Map.get(:metadata, %{}) |> Map.get(:metadata, %{})
|> Map.get(:role, Mobilizon.Actors.get_default_member_role(group)), |> Map.get(:role, Mobilizon.Actors.get_default_member_role(group))
{:ok, %Member{} = member} <-
Mobilizon.Actors.create_member(%{ case Mobilizon.Actors.create_member(%{
role: role, role: role,
parent_id: group.id, parent_id: group.id,
actor_id: actor.id, actor_id: actor.id,
@ -135,20 +147,23 @@ defmodule Mobilizon.Federation.ActivityPub.Types.Actors do
additional additional
|> Map.get(:metadata, %{}) |> Map.get(:metadata, %{})
|> Map.update(:message, nil, &String.trim(HTML.strip_tags(&1))) |> Map.update(:message, nil, &String.trim(HTML.strip_tags(&1)))
}), }) do
{:ok, _} <- {:ok, %Member{} = member} ->
Mobilizon.Service.Activity.Member.insert_activity(member, subject: "member_joined"), Mobilizon.Service.Activity.Member.insert_activity(member, subject: "member_joined")
Absinthe.Subscription.publish(Endpoint, actor, Absinthe.Subscription.publish(Endpoint, actor,
group_membership_changed: [Actor.preferred_username_and_domain(group), actor.id] group_membership_changed: [Actor.preferred_username_and_domain(group), actor.id]
), )
join_data <- %{
join_data = %{
"type" => "Join", "type" => "Join",
"id" => member.url, "id" => member.url,
"actor" => actor.url, "actor" => actor.url,
"object" => group.url "object" => group.url
}, }
audience <-
Audience.get_audience(member) do audience = Audience.get_audience(member)
approve_if_default_role_is_member( approve_if_default_role_is_member(
group, group,
actor, actor,
@ -156,24 +171,32 @@ defmodule Mobilizon.Federation.ActivityPub.Types.Actors do
member, member,
role role
) )
{:error, %Ecto.Changeset{} = err} ->
{:error, err}
end end
end end
@spec follow(Actor.t(), Actor.t(), boolean, map) :: @spec follow(Actor.t(), Actor.t(), boolean, map) ::
{:accept, any} {:accept, any}
| {:ok, ActivityStreams.t(), Follower.t()} | {:ok, ActivityStreams.t(), Follower.t()}
| {:error, :no_person, String.t()} | {:error,
:person_no_follow | :already_following | :followed_suspended | Ecto.Changeset.t()}
def follow(%Actor{} = follower_actor, %Actor{type: type} = followed, _local, additional) def follow(%Actor{} = follower_actor, %Actor{type: type} = followed, _local, additional)
when type != :Person do when type != :Person do
with {:ok, %Follower{} = follower} <- case Mobilizon.Actors.follow(followed, follower_actor, additional["activity_id"], false) do
Mobilizon.Actors.follow(followed, follower_actor, additional["activity_id"], false), {:ok, %Follower{} = follower} ->
:ok <- FollowMailer.send_notification_to_admins(follower), FollowMailer.send_notification_to_admins(follower)
follower_as_data <- Convertible.model_to_as(follower) do follower_as_data = Convertible.model_to_as(follower)
approve_if_manually_approves_followers(follower, follower_as_data) approve_if_manually_approves_followers(follower, follower_as_data)
{:error, error} ->
{:error, error}
end end
end end
def follow(_, _, _, _), do: {:error, :no_person, "Only group and instances can be followed"} # "Only group and instances can be followed"
def follow(_, _, _, _), do: {:error, :person_no_follow}
@spec prepare_args_for_actor(map) :: map @spec prepare_args_for_actor(map) :: map
defp prepare_args_for_actor(args) do defp prepare_args_for_actor(args) do
@ -242,7 +265,10 @@ defmodule Mobilizon.Federation.ActivityPub.Types.Actors do
end end
end end
@spec approve_if_manually_approves_followers(Follower.t(), ActivityStreams.t()) :: @spec approve_if_manually_approves_followers(
follower :: Follower.t(),
follow_as_data :: ActivityStreams.t()
) ::
{:accept, any} | {:ok, ActivityStreams.t(), Follower.t()} {:accept, any} | {:ok, ActivityStreams.t(), Follower.t()}
defp approve_if_manually_approves_followers( defp approve_if_manually_approves_followers(
%Follower{} = follower, %Follower{} = follower,

View File

@ -21,48 +21,56 @@ defmodule Mobilizon.Federation.ActivityPub.Types.Comments do
@behaviour Entity @behaviour Entity
@impl Entity @impl Entity
@spec create(map(), map()) :: {:ok, Comment.t(), ActivityStream.t()} @spec create(map(), map()) ::
{:ok, Comment.t(), ActivityStream.t()}
| {:error, Ecto.Changeset.t()}
| {:error, :event_not_allow_commenting}
def create(args, additional) do def create(args, additional) do
with args <- prepare_args_for_comment(args), args = prepare_args_for_comment(args)
:ok <- make_sure_event_allows_commenting(args),
{:ok, %Comment{discussion_id: discussion_id} = comment} <- if event_allows_commenting?(args) do
Discussions.create_comment(args), case Discussions.create_comment(args) do
{:ok, _} <- {:ok, %Comment{discussion_id: discussion_id} = comment} ->
CommentActivity.insert_activity(comment, CommentActivity.insert_activity(comment,
subject: "comment_posted" subject: "comment_posted"
), )
:ok <- maybe_publish_graphql_subscription(discussion_id),
comment_as_data <- Convertible.model_to_as(comment), maybe_publish_graphql_subscription(discussion_id)
audience <- comment_as_data = Convertible.model_to_as(comment)
Audience.get_audience(comment), audience = Audience.get_audience(comment)
create_data <- create_data = make_create_data(comment_as_data, Map.merge(audience, additional))
make_create_data(comment_as_data, Map.merge(audience, additional)) do
{:ok, comment, create_data} {:ok, comment, create_data}
{:error, %Ecto.Changeset{} = err} ->
{:error, err}
end
else
{:error, :event_not_allow_commenting}
end end
end end
@impl Entity @impl Entity
@spec update(Comment.t(), map(), map()) :: {:ok, Comment.t(), ActivityStream.t()} @spec update(Comment.t(), map(), map()) ::
{:ok, Comment.t(), ActivityStream.t()} | {:error, Ecto.Changeset.t()}
def update(%Comment{} = old_comment, args, additional) do def update(%Comment{} = old_comment, args, additional) do
with args <- prepare_args_for_comment_update(args), args = prepare_args_for_comment_update(args)
{:ok, %Comment{} = new_comment} <- Discussions.update_comment(old_comment, args),
{:ok, true} <- Cachex.del(:activity_pub, "comment_#{new_comment.uuid}"), case Discussions.update_comment(old_comment, args) do
comment_as_data <- Convertible.model_to_as(new_comment), {:ok, %Comment{} = new_comment} ->
audience <- {:ok, true} = Cachex.del(:activity_pub, "comment_#{new_comment.uuid}")
Audience.get_audience(new_comment), comment_as_data = Convertible.model_to_as(new_comment)
update_data <- make_update_data(comment_as_data, Map.merge(audience, additional)) do audience = Audience.get_audience(new_comment)
update_data = make_update_data(comment_as_data, Map.merge(audience, additional))
{:ok, new_comment, update_data} {:ok, new_comment, update_data}
else
err -> {:error, %Ecto.Changeset{} = err} ->
Logger.error("Something went wrong while creating an update activity") {:error, err}
Logger.debug(inspect(err))
err
end end
end end
@impl Entity @impl Entity
@spec delete(Comment.t(), Actor.t(), boolean, map()) :: @spec delete(Comment.t(), Actor.t(), boolean, map()) ::
{:ok, ActivityStream.t(), Actor.t(), Comment.t()} {:ok, ActivityStream.t(), Actor.t(), Comment.t()} | {:error, Ecto.Changeset.t()}
def delete( def delete(
%Comment{url: url, id: comment_id}, %Comment{url: url, id: comment_id},
%Actor{} = actor, %Actor{} = actor,
@ -81,15 +89,17 @@ defmodule Mobilizon.Federation.ActivityPub.Types.Comments do
force_deletion = Map.get(options, :force, false) force_deletion = Map.get(options, :force, false)
with audience <- audience = Audience.get_audience(comment)
Audience.get_audience(comment),
{:ok, %Comment{} = updated_comment} <- case Discussions.delete_comment(comment, force: force_deletion) do
Discussions.delete_comment(comment, force: force_deletion), {:ok, %Comment{} = updated_comment} ->
{:ok, true} <- Cachex.del(:activity_pub, "comment_#{comment.uuid}"), Cachex.del(:activity_pub, "comment_#{comment.uuid}")
{:ok, %Tombstone{} = _tombstone} <- Tombstone.create_tombstone(%{uri: comment.url, actor_id: actor.id})
Tombstone.create_tombstone(%{uri: comment.url, actor_id: actor.id}) do
Share.delete_all_by_uri(comment.url) Share.delete_all_by_uri(comment.url)
{:ok, Map.merge(activity_data, audience), actor, updated_comment} {:ok, Map.merge(activity_data, audience), actor, updated_comment}
{:error, %Ecto.Changeset{} = err} ->
{:error, err}
end end
end end
@ -185,31 +195,31 @@ defmodule Mobilizon.Federation.ActivityPub.Types.Comments do
defp maybe_publish_graphql_subscription(nil), do: :ok defp maybe_publish_graphql_subscription(nil), do: :ok
defp maybe_publish_graphql_subscription(discussion_id) do defp maybe_publish_graphql_subscription(discussion_id) do
with %Discussion{} = discussion <- Discussions.get_discussion(discussion_id) do case Discussions.get_discussion(discussion_id) do
%Discussion{} = discussion ->
Absinthe.Subscription.publish(Endpoint, discussion, Absinthe.Subscription.publish(Endpoint, discussion,
discussion_comment_changed: discussion.slug discussion_comment_changed: discussion.slug
) )
:ok :ok
nil ->
:ok
end end
end end
@spec make_sure_event_allows_commenting(%{actor_id: String.t() | integer, event: Event.t()}) :: @spec event_allows_commenting?(%{actor_id: String.t() | integer, event: Event.t()}) :: boolean
:ok | {:error, :event_comments_are_closed} defp event_allows_commenting?(%{
defp make_sure_event_allows_commenting(%{
actor_id: actor_id, actor_id: actor_id,
event: %Event{ event: %Event{
options: %EventOptions{comment_moderation: comment_moderation}, options: %EventOptions{comment_moderation: comment_moderation},
organizer_actor_id: organizer_actor_id organizer_actor_id: organizer_actor_id
} }
}) do }) do
if comment_moderation != :closed || comment_moderation != :closed ||
to_string(actor_id) == to_string(organizer_actor_id) do to_string(actor_id) == to_string(organizer_actor_id)
:ok
else
{:error, :event_comments_are_closed}
end
end end
defp make_sure_event_allows_commenting(_), do: :ok # Comments not attached to events
defp event_allows_commenting?(_), do: true
end end

View File

@ -43,13 +43,13 @@ defmodule Mobilizon.Federation.ActivityPub.Types.Entity do
| TodoList.t() | TodoList.t()
@callback create(data :: any(), additionnal :: map()) :: @callback create(data :: any(), additionnal :: map()) ::
{:ok, t(), ActivityStream.t()} {:ok, t(), ActivityStream.t()} | {:error, any()}
@callback update(struct :: t(), attrs :: map(), additionnal :: map()) :: @callback update(struct :: t(), attrs :: map(), additionnal :: map()) ::
{:ok, t(), ActivityStream.t()} {:ok, t(), ActivityStream.t()} | {:error, any()}
@callback delete(struct :: t(), Actor.t(), local :: boolean(), map()) :: @callback delete(struct :: t(), Actor.t(), local :: boolean(), map()) ::
{:ok, ActivityStream.t(), Actor.t(), t()} {:ok, ActivityStream.t(), Actor.t(), t()} | {:error, any()}
end end
defprotocol Mobilizon.Federation.ActivityPub.Types.Managable do defprotocol Mobilizon.Federation.ActivityPub.Types.Managable do
@ -57,14 +57,15 @@ defprotocol Mobilizon.Federation.ActivityPub.Types.Managable do
ActivityPub entity Managable protocol. ActivityPub entity Managable protocol.
""" """
@spec update(Entity.t(), map(), map()) :: {:ok, Entity.t(), ActivityStream.t()} @spec update(Entity.t(), map(), map()) ::
{:ok, Entity.t(), ActivityStream.t()} | {:error, any()}
@doc """ @doc """
Updates a `Managable` entity with the appropriate attributes and returns the updated entity and an activitystream representation for it Updates a `Managable` entity with the appropriate attributes and returns the updated entity and an activitystream representation for it
""" """
def update(entity, attrs, additionnal) def update(entity, attrs, additionnal)
@spec delete(Entity.t(), Actor.t(), boolean(), map()) :: @spec delete(Entity.t(), Actor.t(), boolean(), map()) ::
{:ok, ActivityStream.t(), Actor.t(), Entity.t()} {:ok, ActivityStream.t(), Actor.t(), Entity.t()} | {:error, any()}
@doc "Deletes an entity and returns the activitystream representation for it" @doc "Deletes an entity and returns the activitystream representation for it"
def delete(entity, actor, local, additionnal) def delete(entity, actor, local, additionnal)
end end

View File

@ -22,45 +22,53 @@ defmodule Mobilizon.Federation.ActivityPub.Types.Events do
@behaviour Entity @behaviour Entity
@impl Entity @impl Entity
@spec create(map(), map()) :: {:ok, Event.t(), ActivityStream.t()} @spec create(map(), map()) ::
{:ok, Event.t(), ActivityStream.t()} | {:error, Ecto.Changeset.t()}
def create(args, additional) do def create(args, additional) do
with args <- prepare_args_for_event(args), args = prepare_args_for_event(args)
{:ok, %Event{} = event} <- EventsManager.create_event(args),
{:ok, _} <- case EventsManager.create_event(args) do
EventActivity.insert_activity(event, subject: "event_created"), {:ok, %Event{} = event} ->
event_as_data <- Convertible.model_to_as(event), EventActivity.insert_activity(event, subject: "event_created")
audience <- event_as_data = Convertible.model_to_as(event)
Audience.get_audience(event), audience = Audience.get_audience(event)
create_data <- create_data = make_create_data(event_as_data, Map.merge(audience, additional))
make_create_data(event_as_data, Map.merge(audience, additional)) do
{:ok, event, create_data} {:ok, event, create_data}
{:error, _step, %Ecto.Changeset{} = err, _} ->
{:error, err}
{:error, err} ->
{:error, err}
end end
end end
@impl Entity @impl Entity
@spec update(Event.t(), map(), map()) :: {:ok, Event.t(), ActivityStream.t()} @spec update(Event.t(), map(), map()) ::
{:ok, Event.t(), ActivityStream.t()} | {:error, Ecto.Changeset.t()}
def update(%Event{} = old_event, args, additional) do def update(%Event{} = old_event, args, additional) do
with args <- prepare_args_for_event(args), args = prepare_args_for_event(args)
{:ok, %Event{} = new_event} <- EventsManager.update_event(old_event, args),
{:ok, _} <- case EventsManager.update_event(old_event, args) do
EventActivity.insert_activity(new_event, subject: "event_updated"), {:ok, %Event{} = new_event} ->
{:ok, true} <- Cachex.del(:activity_pub, "event_#{new_event.uuid}"), EventActivity.insert_activity(new_event, subject: "event_updated")
event_as_data <- Convertible.model_to_as(new_event), Cachex.del(:activity_pub, "event_#{new_event.uuid}")
audience <- event_as_data = Convertible.model_to_as(new_event)
Audience.get_audience(new_event), audience = Audience.get_audience(new_event)
update_data <- make_update_data(event_as_data, Map.merge(audience, additional)) do update_data = make_update_data(event_as_data, Map.merge(audience, additional))
{:ok, new_event, update_data} {:ok, new_event, update_data}
else
err -> {:error, _step, %Ecto.Changeset{} = err, _} ->
Logger.error("Something went wrong while creating an update activity") {:error, err}
Logger.debug(inspect(err))
err {:error, err} ->
{:error, err}
end end
end end
@impl Entity @impl Entity
@spec delete(Event.t(), Actor.t(), boolean, map()) :: @spec delete(Event.t(), Actor.t(), boolean, map()) ::
{:ok, ActivityStream.t(), Actor.t(), Event.t()} {:ok, ActivityStream.t(), Actor.t(), Event.t()} | {:error, Ecto.Changeset.t()}
def delete(%Event{url: url} = event, %Actor{} = actor, _local, _additionnal) do def delete(%Event{url: url} = event, %Actor{} = actor, _local, _additionnal) do
activity_data = %{ activity_data = %{
"type" => "Delete", "type" => "Delete",
@ -70,16 +78,23 @@ defmodule Mobilizon.Federation.ActivityPub.Types.Events do
"id" => url <> "/delete" "id" => url <> "/delete"
} }
with audience <- audience = Audience.get_audience(event)
Audience.get_audience(event),
{:ok, %Event{} = event} <- EventsManager.delete_event(event), case EventsManager.delete_event(event) do
{:ok, _} <- {:ok, %Event{} = event} ->
EventActivity.insert_activity(event, subject: "event_deleted"), case Tombstone.create_tombstone(%{uri: event.url, actor_id: actor.id}) do
{:ok, true} <- Cachex.del(:activity_pub, "event_#{event.uuid}"), {:ok, %Tombstone{} = _tombstone} ->
{:ok, %Tombstone{} = _tombstone} <- EventActivity.insert_activity(event, subject: "event_deleted")
Tombstone.create_tombstone(%{uri: event.url, actor_id: actor.id}) do Cachex.del(:activity_pub, "event_#{event.uuid}")
Share.delete_all_by_uri(event.url) Share.delete_all_by_uri(event.url)
{:ok, Map.merge(activity_data, audience), actor, event} {:ok, Map.merge(activity_data, audience), actor, event}
{:error, err} ->
{:error, err}
end
{:error, err} ->
{:error, err}
end end
end end
@ -111,16 +126,16 @@ defmodule Mobilizon.Federation.ActivityPub.Types.Events do
@spec join(Event.t(), Actor.t(), boolean, map) :: @spec join(Event.t(), Actor.t(), boolean, map) ::
{:ok, ActivityStreams.t(), Participant.t()} {:ok, ActivityStreams.t(), Participant.t()}
| {:accept, any()}
| {:error, :maximum_attendee_capacity_reached} | {:error, :maximum_attendee_capacity_reached}
def join(%Event{} = event, %Actor{} = actor, _local, additional) do def join(%Event{} = event, %Actor{} = actor, _local, additional) do
with {:maximum_attendee_capacity, true} <- if check_attendee_capacity?(event) do
{:maximum_attendee_capacity, check_attendee_capacity?(event)}, role =
role <-
additional additional
|> Map.get(:metadata, %{}) |> Map.get(:metadata, %{})
|> Map.get(:role, Mobilizon.Events.get_default_participant_role(event)), |> Map.get(:role, Mobilizon.Events.get_default_participant_role(event))
{:ok, %Participant{} = participant} <-
Mobilizon.Events.create_participant(%{ case Mobilizon.Events.create_participant(%{
role: role, role: role,
event_id: event.id, event_id: event.id,
actor_id: actor.id, actor_id: actor.id,
@ -129,18 +144,22 @@ defmodule Mobilizon.Federation.ActivityPub.Types.Events do
additional additional
|> Map.get(:metadata, %{}) |> Map.get(:metadata, %{})
|> Map.update(:message, nil, &String.trim(HTML.strip_tags(&1))) |> Map.update(:message, nil, &String.trim(HTML.strip_tags(&1)))
}), }) do
join_data <- Convertible.model_to_as(participant), {:ok, %Participant{} = participant} ->
audience <- join_data = Convertible.model_to_as(participant)
Audience.get_audience(participant) do audience = Audience.get_audience(participant)
approve_if_default_role_is_participant( approve_if_default_role_is_participant(
event, event,
Map.merge(join_data, audience), Map.merge(join_data, audience),
participant, participant,
role role
) )
{:error, %Ecto.Changeset{} = err} ->
{:error, err}
end
else else
{:maximum_attendee_capacity, false} ->
{:error, :maximum_attendee_capacity_reached} {:error, :maximum_attendee_capacity_reached}
end end
end end
@ -160,7 +179,7 @@ defmodule Mobilizon.Federation.ActivityPub.Types.Events do
ActivityStreams.t(), ActivityStreams.t(),
Participant.t(), Participant.t(),
ParticipantRole.t() ParticipantRole.t()
) :: {:ok, ActivityStreams.t(), Participant.t()} ) :: {:ok, ActivityStreams.t(), Participant.t()} | {:accept, any()}
defp approve_if_default_role_is_participant(event, activity_data, participant, role) do defp approve_if_default_role_is_participant(event, activity_data, participant, role) do
case event do case event do
%Event{attributed_to: %Actor{id: group_id, url: group_url}} -> %Event{attributed_to: %Actor{id: group_id, url: group_url}} ->
@ -175,12 +194,12 @@ defmodule Mobilizon.Federation.ActivityPub.Types.Events do
{:ok, activity_data, participant} {:ok, activity_data, participant}
end end
%Event{local: true} -> %Event{attributed_to: nil, local: true} ->
do_approve(event, activity_data, participant, role, %{ do_approve(event, activity_data, participant, role, %{
"actor" => event.organizer_actor.url "actor" => event.organizer_actor.url
}) })
_ -> %Event{} ->
{:ok, activity_data, participant} {:ok, activity_data, participant}
end end
end end

View File

@ -9,7 +9,9 @@ defmodule Mobilizon.Federation.ActivityPub.Types.Members do
require Logger require Logger
import Mobilizon.Federation.ActivityPub.Utils, only: [make_update_data: 2] import Mobilizon.Federation.ActivityPub.Utils, only: [make_update_data: 2]
@spec update(Member.t(), map, map) :: {:ok, Member.t(), ActivityStream.t()} @spec update(Member.t(), map, map) ::
{:ok, Member.t(), ActivityStream.t()}
| {:error, :member_not_found | :only_admin_left | Ecto.Changeset.t()}
def update( def update(
%Member{ %Member{
parent: %Actor{id: group_id} = group, parent: %Actor{id: group_id} = group,
@ -20,39 +22,46 @@ defmodule Mobilizon.Federation.ActivityPub.Types.Members do
%{role: updated_role} = args, %{role: updated_role} = args,
%{moderator: %Actor{url: moderator_url, id: moderator_id} = moderator} = additional %{moderator: %Actor{url: moderator_url, id: moderator_id} = moderator} = additional
) do ) do
with additional <- Map.delete(additional, :moderator), additional = Map.delete(additional, :moderator)
{:has_rights_to_update_role, {:ok, %Member{role: moderator_role}}}
when moderator_role in [:moderator, :administrator, :creator] <- case Actors.get_member(moderator_id, group_id) do
{:has_rights_to_update_role, Actors.get_member(moderator_id, group_id)}, {:error, :member_not_found} ->
{:is_only_admin, false} <- {:error, :member_not_found}
{:is_only_admin, check_admins_left?(member_id, group_id, current_role, updated_role)},
{:ok, %Member{} = member} <- {:ok, %Member{role: moderator_role}}
Actors.update_member(old_member, args), when moderator_role in [:moderator, :administrator, :creator] ->
{:ok, _} <- if check_admins_left?(member_id, group_id, current_role, updated_role) do
{:error, :only_admin_left}
else
case Actors.update_member(old_member, args) do
{:error, %Ecto.Changeset{} = err} ->
{:error, err}
{:ok, %Member{} = member} ->
MemberActivity.insert_activity(member, MemberActivity.insert_activity(member,
old_member: old_member, old_member: old_member,
moderator: moderator, moderator: moderator,
subject: "member_updated" subject: "member_updated"
), )
Absinthe.Subscription.publish(Endpoint, actor, Absinthe.Subscription.publish(Endpoint, actor,
group_membership_changed: [Actor.preferred_username_and_domain(group), actor_id] group_membership_changed: [Actor.preferred_username_and_domain(group), actor_id]
), )
{:ok, true} <- Cachex.del(:activity_pub, "member_#{member_id}"),
member_as_data <- Cachex.del(:activity_pub, "member_#{member_id}")
Convertible.model_to_as(member), member_as_data = Convertible.model_to_as(member)
audience <- %{
audience = %{
"to" => [member.parent.members_url, member.actor.url], "to" => [member.parent.members_url, member.actor.url],
"cc" => [member.parent.url], "cc" => [member.parent.url],
"actor" => moderator_url, "actor" => moderator_url,
"attributedTo" => [member.parent.url] "attributedTo" => [member.parent.url]
} do }
update_data = make_update_data(member_as_data, Map.merge(audience, additional))
update_data = make_update_data(member_as_data, Map.merge(audience, additional))
{:ok, member, update_data} {:ok, member, update_data}
else end
err -> end
Logger.debug(inspect(err))
err
end end
end end

View File

@ -106,6 +106,7 @@ defmodule Mobilizon.Federation.ActivityPub.Utils do
@doc """ @doc """
Enqueues an activity for federation if it's local Enqueues an activity for federation if it's local
""" """
@spec maybe_federate(activity :: Activity.t()) :: :ok
def maybe_federate(%Activity{local: true} = activity) do def maybe_federate(%Activity{local: true} = activity) do
Logger.debug("Maybe federate an activity") Logger.debug("Maybe federate an activity")
@ -165,12 +166,12 @@ defmodule Mobilizon.Federation.ActivityPub.Utils do
Logger.info("Forwarded activity to external members of the group") Logger.info("Forwarded activity to external members of the group")
:ok :ok
_ -> {:error, _err} ->
Logger.info("Failed to forward activity to external members of the group") Logger.info("Failed to forward activity to external members of the group")
:error :error
end end
_ -> nil ->
:ok :ok
end end
end end
@ -311,7 +312,7 @@ defmodule Mobilizon.Federation.ActivityPub.Utils do
{:ok, media} -> {:ok, media} ->
media media
_ -> {:error, _err} ->
nil nil
end end
end end
@ -509,7 +510,7 @@ defmodule Mobilizon.Federation.ActivityPub.Utils do
@doc """ @doc """
Make add activity data Make add activity data
""" """
@spec make_add_data(map(), map()) :: map() @spec make_add_data(map(), map(), map()) :: map()
def make_add_data(object, target, additional \\ %{}) do def make_add_data(object, target, additional \\ %{}) do
Logger.debug("Making add data") Logger.debug("Making add data")
Logger.debug(inspect(object)) Logger.debug(inspect(object))
@ -530,7 +531,7 @@ defmodule Mobilizon.Federation.ActivityPub.Utils do
@doc """ @doc """
Make move activity data Make move activity data
""" """
@spec make_add_data(map(), map()) :: map() @spec make_move_data(map(), map(), map(), map()) :: map()
def make_move_data(object, origin, target, additional \\ %{}) do def make_move_data(object, origin, target, additional \\ %{}) do
Logger.debug("Making move data") Logger.debug("Making move data")
Logger.debug(inspect(object)) Logger.debug(inspect(object))

View File

@ -38,18 +38,15 @@ defmodule Mobilizon.Federation.ActivityStream.Converter.Comment do
Converts an AP object data to our internal data structure. Converts an AP object data to our internal data structure.
""" """
@impl Converter @impl Converter
@spec as_to_model_data(map) :: map | {:error, any()} @spec as_to_model_data(map) :: map | {:error, atom}
def as_to_model_data(object) do def as_to_model_data(object) do
Logger.debug("We're converting raw ActivityStream data to a comment entity") Logger.debug("We're converting raw ActivityStream data to a comment entity")
Logger.debug(inspect(object)) Logger.debug(inspect(object))
with {%Actor{id: actor_id, domain: actor_domain}, attributed_to} <- tag_object = Map.get(object, "tag", [])
maybe_fetch_actor_and_attributed_to_id(object),
{:tags, tags} <- {:tags, fetch_tags(Map.get(object, "tag", []))}, case maybe_fetch_actor_and_attributed_to_id(object) do
{:mentions, mentions} <- {:ok, %Actor{id: actor_id, domain: actor_domain}, attributed_to} ->
{:mentions, fetch_mentions(Map.get(object, "tag", []))},
discussion <-
Discussions.get_discussion_by_url(Map.get(object, "context")) do
Logger.debug("Inserting full comment") Logger.debug("Inserting full comment")
Logger.debug(inspect(object)) Logger.debug(inspect(object))
@ -64,9 +61,9 @@ defmodule Mobilizon.Federation.ActivityStream.Converter.Comment do
in_reply_to_comment_id: nil, in_reply_to_comment_id: nil,
event_id: nil, event_id: nil,
uuid: object["uuid"], uuid: object["uuid"],
discussion_id: if(is_nil(discussion), do: nil, else: discussion.id), discussion_id: get_discussion_id(object),
tags: tags, tags: fetch_tags(tag_object),
mentions: mentions, mentions: fetch_mentions(tag_object),
local: is_nil(actor_domain), local: is_nil(actor_domain),
visibility: if(Visibility.is_public?(object), do: :public, else: :private), visibility: if(Visibility.is_public?(object), do: :public, else: :private),
published_at: object["published"], published_at: object["published"],
@ -81,9 +78,9 @@ defmodule Mobilizon.Federation.ActivityStream.Converter.Comment do
Logger.debug("Converted object after fetching parents") Logger.debug("Converted object after fetching parents")
Logger.debug(inspect(data)) Logger.debug(inspect(data))
data data
else
{:ok, %Actor{suspended: true}} -> {:error, err} ->
:error {:error, err}
end end
end end
@ -94,9 +91,20 @@ defmodule Mobilizon.Federation.ActivityStream.Converter.Comment do
""" """
@impl Converter @impl Converter
@spec model_to_as(CommentModel.t()) :: map @spec model_to_as(CommentModel.t()) :: map
def model_to_as(%CommentModel{deleted_at: nil} = comment) do def model_to_as(
%CommentModel{
deleted_at: nil,
attributed_to: attributed_to,
actor: %Actor{url: comment_actor_url}
} = comment
) do
to = determine_to(comment) to = determine_to(comment)
attributed_to =
if is_nil(attributed_to),
do: comment_actor_url,
else: Map.get(attributed_to, :url, comment_actor_url)
object = %{ object = %{
"type" => "Note", "type" => "Note",
"to" => to, "to" => to,
@ -104,9 +112,7 @@ defmodule Mobilizon.Federation.ActivityStream.Converter.Comment do
"content" => comment.text, "content" => comment.text,
"mediaType" => "text/html", "mediaType" => "text/html",
"actor" => comment.actor.url, "actor" => comment.actor.url,
"attributedTo" => "attributedTo" => attributed_to,
if(is_nil(comment.attributed_to), do: nil, else: comment.attributed_to.url) ||
comment.actor.url,
"uuid" => comment.uuid, "uuid" => comment.uuid,
"id" => comment.url, "id" => comment.url,
"tag" => build_mentions(comment.mentions) ++ build_tags(comment.tags), "tag" => build_mentions(comment.mentions) ++ build_tags(comment.tags),
@ -132,7 +138,6 @@ defmodule Mobilizon.Federation.ActivityStream.Converter.Comment do
end end
@impl Converter @impl Converter
@spec model_to_as(CommentModel.t()) :: map
def model_to_as(%CommentModel{} = comment) do def model_to_as(%CommentModel{} = comment) do
Convertible.model_to_as(%TombstoneModel{ Convertible.model_to_as(%TombstoneModel{
uri: comment.url, uri: comment.url,
@ -203,4 +208,13 @@ defmodule Mobilizon.Federation.ActivityStream.Converter.Comment do
data data
end end
end end
defp get_discussion_id(%{"context" => context}) do
case Discussions.get_discussion_by_url(context) do
%Discussion{id: discussion_id} -> discussion_id
nil -> nil
end
end
defp get_discussion_id(_object), do: nil
end end

View File

@ -47,7 +47,7 @@ defmodule Mobilizon.Federation.ActivityStream.Converter.Event do
@impl Converter @impl Converter
@spec as_to_model_data(map) :: map() | {:error, any()} | :error @spec as_to_model_data(map) :: map() | {:error, any()} | :error
def as_to_model_data(object) do def as_to_model_data(object) do
with {%Actor{id: actor_id}, attributed_to} <- with {:ok, %Actor{id: actor_id}, attributed_to} <-
maybe_fetch_actor_and_attributed_to_id(object), maybe_fetch_actor_and_attributed_to_id(object),
{:address, address_id} <- {:address, address_id} <-
{:address, get_address(object["location"])}, {:address, get_address(object["location"])},
@ -87,7 +87,7 @@ defmodule Mobilizon.Federation.ActivityStream.Converter.Event do
language: object["inLanguage"] language: object["inLanguage"]
} }
else else
{:ok, %Actor{suspended: true}} -> {:error, _err} ->
:error :error
end end
end end

View File

@ -6,6 +6,7 @@ defmodule Mobilizon.Federation.ActivityStream.Converter.Media do
internal one, and back. internal one, and back.
""" """
alias Mobilizon.Federation.ActivityStream
alias Mobilizon.Medias alias Mobilizon.Medias
alias Mobilizon.Medias.Media, as: MediaModel alias Mobilizon.Medias.Media, as: MediaModel
@ -18,7 +19,7 @@ defmodule Mobilizon.Federation.ActivityStream.Converter.Media do
@doc """ @doc """
Convert a media struct to an ActivityStream representation. Convert a media struct to an ActivityStream representation.
""" """
@spec model_to_as(MediaModel.t()) :: map @spec model_to_as(MediaModel.t()) :: ActivityStream.t()
def model_to_as(%MediaModel{file: file}) do def model_to_as(%MediaModel{file: file}) do
%{ %{
"type" => "Document", "type" => "Document",
@ -31,29 +32,53 @@ defmodule Mobilizon.Federation.ActivityStream.Converter.Media do
@doc """ @doc """
Save media data from raw data and return AS Link data. Save media data from raw data and return AS Link data.
""" """
@spec find_or_create_media(map(), String.t() | integer()) ::
{:ok, MediaModel.t()} | {:error, atom() | String.t() | Ecto.Changeset.t()}
def find_or_create_media(%{"type" => "Link", "href" => url}, actor_id), def find_or_create_media(%{"type" => "Link", "href" => url}, actor_id),
do: find_or_create_media(url, actor_id) do:
find_or_create_media(
%{"type" => "Document", "url" => url, "name" => "External media"},
actor_id
)
def find_or_create_media( def find_or_create_media(
%{"type" => "Document", "url" => media_url, "name" => name}, %{"type" => "Document", "url" => media_url, "name" => name},
actor_id actor_id
) )
when is_binary(media_url) do when is_binary(media_url) do
with {:ok, %{body: body}} <- Tesla.get(media_url, opts: @http_options), case upload_media(media_url, name) do
{:ok, %{url: url} = uploaded} <- {:error, err} ->
Upload.store(%{body: body, name: name}), {:error, err}
{:media_exists, nil} <- {:media_exists, Medias.get_media_by_url(url)} do
{:ok, %{url: url} = uploaded} ->
case Medias.get_media_by_url(url) do
%MediaModel{file: _file} = media ->
{:ok, media}
nil ->
Medias.create_media(%{ Medias.create_media(%{
file: Map.take(uploaded, [:url, :name, :content_type, :size]), file: Map.take(uploaded, [:url, :name, :content_type, :size]),
metadata: Map.take(uploaded, [:width, :height, :blurhash]), metadata: Map.take(uploaded, [:width, :height, :blurhash]),
actor_id: actor_id actor_id: actor_id
}) })
else end
{:media_exists, %MediaModel{file: _file} = media} -> end
{:ok, media} end
err -> @spec upload_media(String.t(), String.t()) :: {:ok, map()} | {:error, atom() | String.t()}
err defp upload_media(media_url, name) do
case Tesla.get(media_url, opts: @http_options) do
{:ok, %{body: body}} ->
case Upload.store(%{body: body, name: name}) do
{:ok, %{url: _url} = uploaded} ->
{:ok, uploaded}
{:error, err} ->
{:error, err}
end
{:error, err} ->
{:error, err}
end end
end end
end end

View File

@ -51,10 +51,10 @@ defmodule Mobilizon.Federation.ActivityStream.Converter.Todo do
def as_to_model_data( def as_to_model_data(
%{"type" => "Todo", "actor" => actor_url, "todoList" => todo_list_url} = object %{"type" => "Todo", "actor" => actor_url, "todoList" => todo_list_url} = object
) do ) do
with {:ok, %Actor{id: creator_id} = _creator} <- case ActivityPubActor.get_or_fetch_actor_by_url(actor_url) do
ActivityPubActor.get_or_fetch_actor_by_url(actor_url), {:ok, %Actor{id: creator_id} = _creator} ->
{:todo_list, %TodoList{id: todo_list_id}} <- case Todos.get_todo_list_by_url(todo_list_url) do
{:todo_list, Todos.get_todo_list_by_url(todo_list_url)} do %TodoList{id: todo_list_id} ->
%{ %{
title: object["name"], title: object["name"],
status: object["status"], status: object["status"],
@ -63,11 +63,19 @@ defmodule Mobilizon.Federation.ActivityStream.Converter.Todo do
creator_id: creator_id, creator_id: creator_id,
published_at: object["published"] published_at: object["published"]
} }
else
{:todo_list, nil} -> nil ->
with {:ok, %TodoList{}} <- ActivityPub.fetch_object_from_url(todo_list_url) do case ActivityPub.fetch_object_from_url(todo_list_url) do
{:ok, %TodoList{}} ->
as_to_model_data(object) as_to_model_data(object)
{:error, err} ->
{:error, err}
end end
end end
{:error, err} ->
{:error, err}
end
end end
end end

View File

@ -111,7 +111,6 @@ defmodule Mobilizon.Federation.ActivityStream.Converter.Utils do
acc ++ [%{actor_id: actor_id}] acc ++ [%{actor_id: actor_id}]
end end
@spec create_mention(map(), list()) :: list()
defp create_mention(mention, acc) when is_map(mention) do defp create_mention(mention, acc) when is_map(mention) do
with true <- mention["type"] == "Mention", with true <- mention["type"] == "Mention",
{:ok, %Actor{id: actor_id}} <- {:ok, %Actor{id: actor_id}} <-
@ -128,22 +127,34 @@ defmodule Mobilizon.Federation.ActivityStream.Converter.Utils do
create_mention(mention, acc) create_mention(mention, acc)
end end
@spec maybe_fetch_actor_and_attributed_to_id(map()) :: {Actor.t() | nil, Actor.t() | nil} @spec maybe_fetch_actor_and_attributed_to_id(map()) ::
{:ok, Actor.t(), Actor.t() | nil} | {:error, atom()}
def maybe_fetch_actor_and_attributed_to_id(%{ def maybe_fetch_actor_and_attributed_to_id(%{
"actor" => actor_url, "actor" => actor_url,
"attributedTo" => attributed_to_url "attributedTo" => attributed_to_url
}) })
when is_nil(attributed_to_url) do when is_nil(attributed_to_url) do
{fetch_actor(actor_url), nil} case fetch_actor(actor_url) do
{:ok, %Actor{} = actor} ->
{:ok, actor, nil}
{:error, err} ->
{:error, err}
end
end end
@spec maybe_fetch_actor_and_attributed_to_id(map()) :: {Actor.t() | nil, Actor.t() | nil}
def maybe_fetch_actor_and_attributed_to_id(%{ def maybe_fetch_actor_and_attributed_to_id(%{
"actor" => actor_url, "actor" => actor_url,
"attributedTo" => attributed_to_url "attributedTo" => attributed_to_url
}) })
when is_nil(actor_url) do when is_nil(actor_url) do
{fetch_actor(attributed_to_url), nil} case fetch_actor(attributed_to_url) do
{:ok, %Actor{} = actor} ->
{:ok, actor, nil}
{:error, err} ->
{:error, err}
end
end end
# Only when both actor and attributedTo fields are both filled is when we can return both # Only when both actor and attributedTo fields are both filled is when we can return both
@ -152,9 +163,12 @@ defmodule Mobilizon.Federation.ActivityStream.Converter.Utils do
"attributedTo" => attributed_to_url "attributedTo" => attributed_to_url
}) })
when actor_url != attributed_to_url do when actor_url != attributed_to_url do
with actor <- fetch_actor(actor_url), with {:ok, %Actor{} = actor} <- fetch_actor(actor_url),
attributed_to <- fetch_actor(attributed_to_url) do {:ok, %Actor{} = attributed_to} <- fetch_actor(attributed_to_url) do
{actor, attributed_to} {:ok, actor, attributed_to}
else
{:error, err} ->
{:error, err}
end end
end end
@ -162,16 +176,25 @@ defmodule Mobilizon.Federation.ActivityStream.Converter.Utils do
def maybe_fetch_actor_and_attributed_to_id(%{ def maybe_fetch_actor_and_attributed_to_id(%{
"attributedTo" => attributed_to_url "attributedTo" => attributed_to_url
}) do }) do
{fetch_actor(attributed_to_url), nil} case fetch_actor(attributed_to_url) do
{:ok, %Actor{} = attributed_to} -> {:ok, attributed_to, nil}
{:error, err} -> {:error, err}
end
end end
def maybe_fetch_actor_and_attributed_to_id(_), do: {nil, nil} def maybe_fetch_actor_and_attributed_to_id(_), do: {:error, :no_actor_found}
@spec fetch_actor(String.t()) :: Actor.t() @spec fetch_actor(String.t()) :: {:ok, Actor.t()} | {:error, atom()}
defp fetch_actor(actor_url) do defp fetch_actor(actor_url) do
with {:ok, %Actor{suspended: false} = actor} <- case ActivityPubActor.get_or_fetch_actor_by_url(actor_url) do
ActivityPubActor.get_or_fetch_actor_by_url(actor_url) do {:ok, %Actor{suspended: false} = actor} ->
actor {:ok, actor}
{:ok, %Actor{suspended: true} = _actor} ->
{:error, :actor_suspended}
{:error, err} ->
{:error, err}
end end
end end
@ -203,12 +226,17 @@ defmodule Mobilizon.Federation.ActivityStream.Converter.Utils do
|> Map.new() |> Map.new()
picture_id = picture_id =
with banner when is_map(banner) <- get_banner_picture(attachements), case get_banner_picture(attachements) do
{:ok, %Media{id: picture_id}} <- banner when is_map(banner) ->
MediaConverter.find_or_create_media(banner, actor_id) do case MediaConverter.find_or_create_media(banner, actor_id) do
{:error, _err} ->
nil
{:ok, %Media{id: picture_id}} ->
picture_id picture_id
else end
_err ->
_ ->
nil nil
end end

View File

@ -87,12 +87,16 @@ defmodule Mobilizon.Federation.HTTPSignatures.Signature do
:ok <- Logger.debug("Fetching public key for #{actor_id}"), :ok <- Logger.debug("Fetching public key for #{actor_id}"),
{:ok, public_key} <- get_public_key_for_url(actor_id) do {:ok, public_key} <- get_public_key_for_url(actor_id) do
{:ok, public_key} {:ok, public_key}
else
{:error, err} ->
{:error, err}
end end
end end
@spec refetch_public_key(Plug.Conn.t()) :: @spec refetch_public_key(Plug.Conn.t()) ::
{:ok, String.t()} {:ok, String.t()}
| {:error, :actor_fetch_error | :actor_not_fetchable | :pem_decode_error} | {:error, :actor_fetch_error | :actor_not_fetchable | :pem_decode_error,
:actor_is_local}
def refetch_public_key(conn) do def refetch_public_key(conn) do
with %{"keyId" => kid} <- HTTPSignatures.signature_for_conn(conn), with %{"keyId" => kid} <- HTTPSignatures.signature_for_conn(conn),
actor_id <- key_id_to_actor_url(kid), actor_id <- key_id_to_actor_url(kid),
@ -100,10 +104,13 @@ defmodule Mobilizon.Federation.HTTPSignatures.Signature do
{:ok, _actor} <- ActivityPubActor.make_actor_from_url(actor_id), {:ok, _actor} <- ActivityPubActor.make_actor_from_url(actor_id),
{:ok, public_key} <- get_public_key_for_url(actor_id) do {:ok, public_key} <- get_public_key_for_url(actor_id) do
{:ok, public_key} {:ok, public_key}
else
{:error, err} ->
{:error, err}
end end
end end
@spec sign(Actor.t(), map()) :: String.t() @spec sign(Actor.t(), map()) :: String.t() | {:error, :pem_decode_error} | no_return
def sign(%Actor{domain: domain, keys: keys} = actor, headers) when is_nil(domain) do def sign(%Actor{domain: domain, keys: keys} = actor, headers) when is_nil(domain) do
Logger.debug("Signing a payload on behalf of #{actor.url}") Logger.debug("Signing a payload on behalf of #{actor.url}")
Logger.debug("headers") Logger.debug("headers")

View File

@ -27,7 +27,7 @@ defmodule Mobilizon.Federation.WebFinger do
base_url = Endpoint.url() base_url = Endpoint.url()
%URI{host: host} = URI.parse(base_url) %URI{host: host} = URI.parse(base_url)
{ XmlBuilder.to_doc({
:XRD, :XRD,
%{ %{
xmlns: "http://docs.oasis-open.org/ns/xri/xrd-1.0", xmlns: "http://docs.oasis-open.org/ns/xri/xrd-1.0",
@ -47,8 +47,7 @@ defmodule Mobilizon.Federation.WebFinger do
} }
} }
] ]
} })
|> XmlBuilder.to_doc()
end end
@doc """ @doc """
@ -150,7 +149,7 @@ defmodule Mobilizon.Federation.WebFinger do
{:error, err} -> {:error, err} ->
Logger.debug("Couldn't process webfinger data for #{actor}") Logger.debug("Couldn't process webfinger data for #{actor}")
err {:error, err}
end end
{:error, err} -> {:error, err} ->
@ -187,7 +186,8 @@ defmodule Mobilizon.Federation.WebFinger do
end end
end end
# Fetches the Extensible Resource Descriptor endpoint `/.well-known/host-meta` to find the Webfinger endpoint (usually `/.well-known/webfinger?resource=`) # Fetches the Extensible Resource Descriptor endpoint `/.well-known/host-meta`
# to find the Webfinger endpoint (usually `/.well-known/webfinger?resource=`)
@spec find_webfinger_endpoint(String.t()) :: @spec find_webfinger_endpoint(String.t()) ::
{:ok, String.t()} | {:error, :link_not_found} | {:error, any()} {:ok, String.t()} | {:error, :link_not_found} | {:error, any()}
defp find_webfinger_endpoint(domain) when is_binary(domain) do defp find_webfinger_endpoint(domain) when is_binary(domain) do

View File

@ -5,42 +5,54 @@
defmodule Mobilizon.Federation.WebFinger.XmlBuilder do defmodule Mobilizon.Federation.WebFinger.XmlBuilder do
@moduledoc """ @moduledoc """
Builds XRD for WebFinger host_meta. Extremely basic XML encoder. Builds XRD for WebFinger host_meta.
""" """
def to_xml({tag, attributes, content}) do @typep content :: list({tag :: atom(), attributes :: map()}) | String.t()
@typep document :: {tag :: atom(), attributes :: map(), content :: content}
@doc """
Return the XML representation for a document.
"""
@spec to_doc(document :: document) :: String.t()
def to_doc(document), do: ~s(<?xml version="1.0" encoding="UTF-8"?>) <> to_xml(document)
@spec to_xml(document) :: String.t()
@spec to_xml({tag :: atom(), attributes :: map()}) :: String.t()
@spec to_xml({tag :: atom(), content :: content}) :: String.t()
@spec to_xml(content :: content) :: String.t()
defp to_xml({tag, attributes, content}) do
open_tag = make_open_tag(tag, attributes) open_tag = make_open_tag(tag, attributes)
content_xml = to_xml(content) content_xml = to_xml(content)
"<#{open_tag}>#{content_xml}</#{tag}>" "<#{open_tag}>#{content_xml}</#{tag}>"
end end
def to_xml({tag, %{} = attributes}) do defp to_xml({tag, %{} = attributes}) do
open_tag = make_open_tag(tag, attributes) open_tag = make_open_tag(tag, attributes)
"<#{open_tag} />" "<#{open_tag} />"
end end
def to_xml({tag, content}), do: to_xml({tag, %{}, content}) defp to_xml({tag, content}), do: to_xml({tag, %{}, content})
def to_xml(content) when is_binary(content), do: to_string(content) defp to_xml(content) when is_binary(content), do: to_string(content)
def to_xml(content) when is_list(content) do defp to_xml(content) when is_list(content) do
content content
|> Enum.map(&to_xml/1) |> Enum.map(&to_xml/1)
|> Enum.join() |> Enum.join()
end end
def to_xml(%NaiveDateTime{} = time), do: NaiveDateTime.to_iso8601(time) defp to_xml(%NaiveDateTime{} = time), do: NaiveDateTime.to_iso8601(time)
def to_doc(content), do: ~s(<?xml version="1.0" encoding="UTF-8"?>) <> to_xml(content)
@spec make_open_tag(tag :: atom, attributes :: map()) :: String.t()
defp make_open_tag(tag, attributes) do defp make_open_tag(tag, attributes) do
attributes_string = attributes_string =
attributes attributes
|> Enum.map(fn {attribute, value} -> "#{attribute}=\"#{value}\"" end) |> Enum.map(fn {attribute, value} -> "#{attribute}=\"#{value}\"" end)
|> Enum.join(" ") |> Enum.join(" ")
[tag, attributes_string] |> Enum.join(" ") |> String.trim() [to_string(tag), attributes_string] |> Enum.join(" ") |> String.trim()
end end
end end

View File

@ -15,15 +15,8 @@ defmodule Mobilizon.GraphQL.API.Events do
""" """
@spec create_event(map) :: {:ok, Activity.t(), Event.t()} | any @spec create_event(map) :: {:ok, Activity.t(), Event.t()} | any
def create_event(args) do def create_event(args) do
with organizer_actor <- Map.get(args, :organizer_actor),
args <- extract_pictures_from_event_body(args, organizer_actor),
args <-
Map.update(args, :picture, nil, fn picture ->
process_picture(picture, organizer_actor)
end) do
# For now we don't federate drafts but it will be needed if we want to edit them as groups # For now we don't federate drafts but it will be needed if we want to edit them as groups
ActivityPub.create(:event, args, should_federate(args)) ActivityPub.create(:event, prepare_args(args), should_federate(args))
end
end end
@doc """ @doc """
@ -31,23 +24,28 @@ defmodule Mobilizon.GraphQL.API.Events do
""" """
@spec update_event(map, Event.t()) :: {:ok, Activity.t(), Event.t()} | any @spec update_event(map, Event.t()) :: {:ok, Activity.t(), Event.t()} | any
def update_event(args, %Event{} = event) do def update_event(args, %Event{} = event) do
with organizer_actor <- Map.get(args, :organizer_actor), ActivityPub.update(event, prepare_args(args), should_federate(args))
args <- extract_pictures_from_event_body(args, organizer_actor),
args <-
Map.update(args, :picture, nil, fn picture ->
process_picture(picture, organizer_actor)
end) do
ActivityPub.update(event, args, should_federate(args))
end
end end
@doc """ @doc """
Trigger the deletion of an event Trigger the deletion of an event
""" """
@spec delete_event(Event.t(), Actor.t(), boolean()) :: {:ok, Activity.t(), Entity.t()} | any()
def delete_event(%Event{} = event, %Actor{} = actor, federate \\ true) do def delete_event(%Event{} = event, %Actor{} = actor, federate \\ true) do
ActivityPub.delete(event, actor, federate) ActivityPub.delete(event, actor, federate)
end end
@spec prepare_args(map) :: map
defp prepare_args(args) do
organizer_actor = Map.get(args, :organizer_actor)
args
|> extract_pictures_from_event_body(organizer_actor)
|> Map.update(:picture, nil, fn picture ->
process_picture(picture, organizer_actor)
end)
end
defp process_picture(nil, _), do: nil defp process_picture(nil, _), do: nil
defp process_picture(%{media_id: _picture_id} = args, _), do: args defp process_picture(%{media_id: _picture_id} = args, _), do: args
@ -75,6 +73,7 @@ defmodule Mobilizon.GraphQL.API.Events do
defp extract_pictures_from_event_body(args, _), do: args defp extract_pictures_from_event_body(args, _), do: args
@spec should_federate(map()) :: boolean
defp should_federate(%{attributed_to_id: attributed_to_id}) when not is_nil(attributed_to_id), defp should_federate(%{attributed_to_id: attributed_to_id}) when not is_nil(attributed_to_id),
do: true do: true

View File

@ -7,72 +7,80 @@ defmodule Mobilizon.GraphQL.API.Follows do
alias Mobilizon.Actors.{Actor, Follower} alias Mobilizon.Actors.{Actor, Follower}
alias Mobilizon.Federation.ActivityPub alias Mobilizon.Federation.ActivityPub
alias Mobilizon.Federation.ActivityPub.Activity
require Logger require Logger
@doc """
Make an actor (`follower`) follow another (`followed`).
"""
@spec follow(follower :: Actor.t(), followed :: Actor.t()) ::
{:ok, Mobilizon.Federation.ActivityPub.Activity.t(), Mobilizon.Actors.Follower.t()}
| {:error, String.t()}
def follow(%Actor{} = follower, %Actor{} = followed) do def follow(%Actor{} = follower, %Actor{} = followed) do
case ActivityPub.follow(follower, followed) do ActivityPub.follow(follower, followed)
{:ok, activity, follow} ->
{:ok, activity, follow}
{:error, e} ->
Logger.warn("Error while following actor: #{inspect(e)}")
{:error, e}
e ->
Logger.warn("Error while following actor: #{inspect(e)}")
{:error, e}
end
end end
@doc """
Make an actor (`follower`) unfollow another (`followed`).
"""
@spec unfollow(follower :: Actor.t(), followed :: Actor.t()) ::
{:ok, Mobilizon.Federation.ActivityPub.Activity.t(), Mobilizon.Actors.Follower.t()}
| {:error, String.t()}
def unfollow(%Actor{} = follower, %Actor{} = followed) do def unfollow(%Actor{} = follower, %Actor{} = followed) do
case ActivityPub.unfollow(follower, followed) do ActivityPub.unfollow(follower, followed)
{:ok, activity, follow} ->
{:ok, activity, follow}
e ->
Logger.warn("Error while unfollowing actor: #{inspect(e)}")
{:error, e}
end
end end
def accept(%Actor{} = follower, %Actor{} = followed) do @doc """
Logger.debug("We're trying to accept a follow") Make an actor (`followed`) accept the follow from another (`follower`).
"""
@spec accept(follower :: Actor.t(), followed :: Actor.t()) ::
{:ok, Mobilizon.Federation.ActivityPub.Activity.t(), Mobilizon.Actors.Follower.t()}
| {:error, String.t()}
def accept(%Actor{url: follower_url} = follower, %Actor{url: followed_url} = followed) do
Logger.debug(
"We're trying to accept a follow: #{followed_url} is accepting #{follower_url} follow request."
)
with %Follower{approved: false} = follow <- case Actors.is_following(follower, followed) do
Actors.is_following(follower, followed), %Follower{approved: false} = follow ->
{:ok, %Activity{} = activity, %Follower{approved: true} = follow} <-
ActivityPub.accept( ActivityPub.accept(
:follow, :follow,
follow, follow,
true true
) do )
{:ok, activity, follow}
else
%Follower{approved: true} -> %Follower{approved: true} ->
{:error, "Follow already accepted"} {:error, "Follow already accepted"}
nil ->
{:error, "Can't accept follow: #{follower_url} is not following #{followed_url}."}
end end
end end
def reject(%Actor{} = follower, %Actor{} = followed) do @doc """
Logger.debug("We're trying to reject a follow") Make an actor (`followed`) reject the follow from another (`follower`).
"""
@spec reject(follower :: Actor.t(), followed :: Actor.t()) ::
{:ok, Mobilizon.Federation.ActivityPub.Activity.t(), Mobilizon.Actors.Follower.t()}
| {:error, String.t()}
def reject(%Actor{url: follower_url} = follower, %Actor{url: followed_url} = followed) do
Logger.debug(
"We're trying to reject a follow: #{followed_url} is rejecting #{follower_url} follow request."
)
with {:follower, %Follower{} = follow} <- case Actors.is_following(follower, followed) do
{:follower, Actors.is_following(follower, followed)}, %Follower{approved: true} ->
{:ok, %Activity{} = activity, %Follower{} = follow} <- {:error, "Follow already accepted"}
%Follower{} = follow ->
ActivityPub.reject( ActivityPub.reject(
:follow, :follow,
follow, follow,
true true
) do )
{:ok, activity, follow}
else
{:follower, nil} ->
{:error, "Follow not found"}
{:follower, %Follower{approved: true}} -> nil ->
{:error, "Follow already accepted"} {:error, "Follow not found"}
end end
end end
end end

View File

@ -11,23 +11,23 @@ defmodule Mobilizon.GraphQL.API.Participations do
alias Mobilizon.Service.Notifications.Scheduler alias Mobilizon.Service.Notifications.Scheduler
alias Mobilizon.Web.Email.Participation alias Mobilizon.Web.Email.Participation
@spec join(Event.t(), Actor.t(), map()) :: {:ok, Activity.t(), Participant.t()} @spec join(Event.t(), Actor.t(), map()) ::
{:ok, Activity.t(), Participant.t()} | {:error, :already_participant}
def join(%Event{id: event_id} = event, %Actor{id: actor_id} = actor, args \\ %{}) do def join(%Event{id: event_id} = event, %Actor{id: actor_id} = actor, args \\ %{}) do
with {:error, :participant_not_found} <- case Mobilizon.Events.get_participant(event_id, actor_id, args) do
Mobilizon.Events.get_participant(event_id, actor_id, args), {:ok, %Participant{}} ->
{:ok, activity, participant} <- {:error, :already_participant}
ActivityPub.join(event, actor, Map.get(args, :local, true), %{metadata: args}) do
{:ok, activity, participant} {:error, :participant_not_found} ->
ActivityPub.join(event, actor, Map.get(args, :local, true), %{metadata: args})
end end
end end
@spec leave(Event.t(), Actor.t()) :: {:ok, Activity.t(), Participant.t()} @spec leave(Event.t(), Actor.t(), map()) ::
def leave(%Event{} = event, %Actor{} = actor, args \\ %{}) do {:ok, Activity.t(), Participant.t()}
with {:ok, activity, participant} <- | {:error, :is_only_organizer | :participant_not_found | Ecto.Changeset.t()}
ActivityPub.leave(event, actor, Map.get(args, :local, true), %{metadata: args}) do def leave(%Event{} = event, %Actor{} = actor, args \\ %{}),
{:ok, activity, participant} do: ActivityPub.leave(event, actor, Map.get(args, :local, true), %{metadata: args})
end
end
@doc """ @doc """
Update participation status Update participation status
@ -36,7 +36,6 @@ defmodule Mobilizon.GraphQL.API.Participations do
def update(%Participant{} = participation, %Actor{} = moderator, :participant), def update(%Participant{} = participation, %Actor{} = moderator, :participant),
do: accept(participation, moderator) do: accept(participation, moderator)
@spec update(Participant.t(), Actor.t(), atom()) :: {:ok, Activity.t(), Participant.t()}
def update(%Participant{} = participation, %Actor{} = _moderator, :not_approved) do def update(%Participant{} = participation, %Actor{} = _moderator, :not_approved) do
with {:ok, %Participant{} = participant} <- with {:ok, %Participant{} = participant} <-
Events.update_participant(participation, %{role: :not_approved}) do Events.update_participant(participation, %{role: :not_approved}) do
@ -45,7 +44,6 @@ defmodule Mobilizon.GraphQL.API.Participations do
end end
end end
@spec update(Participant.t(), Actor.t(), atom()) :: {:ok, Activity.t(), Participant.t()}
def update(%Participant{} = participation, %Actor{} = moderator, :rejected), def update(%Participant{} = participation, %Actor{} = moderator, :rejected),
do: reject(participation, moderator) do: reject(participation, moderator)

View File

@ -59,8 +59,8 @@ defmodule Mobilizon.GraphQL.API.Search do
@doc """ @doc """
Search events Search events
""" """
@spec search_events(String.t(), integer | nil, integer | nil) :: @spec search_events(map(), integer | nil, integer | nil) ::
{:ok, Page.t()} | {:error, String.t()} {:ok, Page.t()}
def search_events(%{term: term} = args, page \\ 1, limit \\ 10) do def search_events(%{term: term} = args, page \\ 1, limit \\ 10) do
term = String.trim(term) term = String.trim(term)
@ -78,6 +78,7 @@ defmodule Mobilizon.GraphQL.API.Search do
end end
end end
@spec interact(String.t()) :: {:ok, struct()} | {:error, :not_found}
def interact(uri) do def interact(uri) do
case ActivityPub.fetch_object_from_url(uri) do case ActivityPub.fetch_object_from_url(uri) do
{:ok, object} -> {:ok, object} ->

View File

@ -15,8 +15,9 @@ defmodule Mobilizon.GraphQL.Resolvers.Activity do
def group_activity(%Actor{type: :Group, id: group_id}, %{page: page, limit: limit} = args, %{ def group_activity(%Actor{type: :Group, id: group_id}, %{page: page, limit: limit} = args, %{
context: %{current_user: %User{role: role} = user} context: %{current_user: %User{role: role} = user}
}) do }) do
with {:actor, %Actor{id: actor_id} = _actor} <- {:actor, Users.get_actor_for_user(user)}, case Users.get_actor_for_user(user) do
{:member, true} <- {:member, Actors.is_member?(actor_id, group_id) or is_moderator(role)} do %Actor{id: actor_id} = _actor ->
if Actors.is_member?(actor_id, group_id) or is_moderator(role) do
%Page{total: total, elements: elements} = %Page{total: total, elements: elements} =
Activities.list_group_activities_for_member( Activities.list_group_activities_for_member(
group_id, group_id,
@ -30,9 +31,12 @@ defmodule Mobilizon.GraphQL.Resolvers.Activity do
{:ok, %Page{total: total, elements: elements}} {:ok, %Page{total: total, elements: elements}}
else else
{:member, false} ->
{:error, :unauthorized} {:error, :unauthorized}
end end
nil ->
{:error, :user_actor_not_found}
end
end end
def group_activity(_, _, _) do def group_activity(_, _, _) do

View File

@ -311,7 +311,7 @@ defmodule Mobilizon.GraphQL.Resolvers.Admin do
{:ok, _activity, follow} -> {:ok, _activity, follow} ->
{:ok, follow} {:ok, follow}
{:error, err} when is_binary(err) -> {:error, err} ->
{:error, err} {:error, err}
end end
end end
@ -322,7 +322,7 @@ defmodule Mobilizon.GraphQL.Resolvers.Admin do
{:ok, _activity, follow} -> {:ok, _activity, follow} ->
{:ok, follow} {:ok, follow}
{:error, {:error, err}} when is_binary(err) -> {:error, err} ->
{:error, err} {:error, err}
end end
end end
@ -337,10 +337,7 @@ defmodule Mobilizon.GraphQL.Resolvers.Admin do
{:ok, _activity, follow} -> {:ok, _activity, follow} ->
{:ok, follow} {:ok, follow}
{:error, {:error, err}} when is_binary(err) -> {:error, err} ->
{:error, err}
{:error, err} when is_binary(err) ->
{:error, err} {:error, err}
end end
end end
@ -355,10 +352,7 @@ defmodule Mobilizon.GraphQL.Resolvers.Admin do
{:ok, _activity, follow} -> {:ok, _activity, follow} ->
{:ok, follow} {:ok, follow}
{:error, {:error, err}} when is_binary(err) -> {:error, err} ->
{:error, err}
{:error, err} when is_binary(err) ->
{:error, err} {:error, err}
end end
end end
@ -385,16 +379,18 @@ defmodule Mobilizon.GraphQL.Resolvers.Admin do
do: Map.put(args, :name, new_instance_name), do: Map.put(args, :name, new_instance_name),
else: args else: args
with {:changes, true} <- {:changes, args != %{}}, if args != %{} do
%Actor{} = instance_actor <- Relay.get_actor(), %Actor{} = instance_actor = Relay.get_actor()
{:ok, _activity, _actor} <- ActivityPub.update(instance_actor, args, true) do
:ok case ActivityPub.update(instance_actor, args, true) do
else {:ok, _activity, _actor} ->
{:changes, false} ->
:ok :ok
err -> {:error, _err} ->
err {:error, :instance_actor_update_failure}
end
else
:ok
end end
end end
end end

View File

@ -293,8 +293,9 @@ defmodule Mobilizon.GraphQL.Resolvers.Event do
%{context: %{current_user: %User{} = user}} = _resolution %{context: %{current_user: %User{} = user}} = _resolution
) do ) do
# See https://github.com/absinthe-graphql/absinthe/issues/490 # See https://github.com/absinthe-graphql/absinthe/issues/490
with args <- Map.put(args, :options, args[:options] || %{}), args = Map.put(args, :options, args[:options] || %{})
{:ok, %Event{} = event} <- Events.get_event_with_preload(event_id),
with {:ok, %Event{} = event} <- Events.get_event_with_preload(event_id),
%Actor{} = actor <- Users.get_actor_for_user(user), %Actor{} = actor <- Users.get_actor_for_user(user),
{:ok, args} <- verify_profile_change(args, event, user, actor), {:ok, args} <- verify_profile_change(args, event, user, actor),
{:event_can_be_managed, true} <- {:event_can_be_managed, true} <-
@ -319,7 +320,7 @@ defmodule Mobilizon.GraphQL.Resolvers.Event do
{:new_actor, _} -> {:new_actor, _} ->
{:error, dgettext("errors", "You can't attribute this event to this profile.")} {:error, dgettext("errors", "You can't attribute this event to this profile.")}
{:error, _, %Ecto.Changeset{} = error, _} -> {:error, %Ecto.Changeset{} = error} ->
{:error, error} {:error, error}
end end
end end

View File

@ -94,6 +94,7 @@ defmodule Mobilizon.GraphQL.Resolvers.Media do
else else
{:media, nil} -> {:error, :not_found} {:media, nil} -> {:error, :not_found}
{:is_owned, _} -> {:error, :unauthorized} {:is_owned, _} -> {:error, :unauthorized}
{:error, :enofile} -> {:error, "File not found"}
end end
end end

View File

@ -145,10 +145,10 @@ defmodule Mobilizon.GraphQL.Resolvers.Member do
ActivityPub.update(member, %{role: role}, true, %{moderator: moderator}) do ActivityPub.update(member, %{role: role}, true, %{moderator: moderator}) do
{:ok, member} {:ok, member}
else else
{:has_rights_to_update_role, {:error, :member_not_found}} -> {:error, :member_not_found} ->
{:error, dgettext("errors", "You are not a moderator or admin for this group")} {:error, dgettext("errors", "You are not a moderator or admin for this group")}
{:is_only_admin, true} -> {:error, :only_admin_left} ->
{:error, {:error,
dgettext( dgettext(
"errors", "errors",

View File

@ -117,7 +117,7 @@ defmodule Mobilizon.GraphQL.Resolvers.Participant do
|> Map.put(:actor, actor) do |> Map.put(:actor, actor) do
{:ok, participant} {:ok, participant}
else else
{:maximum_attendee_capacity, _} -> {:error, :maximum_attendee_capacity_reached} ->
{:error, dgettext("errors", "The event has already reached its maximum capacity")} {:error, dgettext("errors", "The event has already reached its maximum capacity")}
{:has_event, _} -> {:has_event, _} ->
@ -127,11 +127,33 @@ defmodule Mobilizon.GraphQL.Resolvers.Participant do
{:error, :event_not_found} -> {:error, :event_not_found} ->
{:error, dgettext("errors", "Event id not found")} {:error, dgettext("errors", "Event id not found")}
{:ok, %Participant{}} -> {:error, :already_participant} ->
{:error, dgettext("errors", "You are already a participant of this event")} {:error, dgettext("errors", "You are already a participant of this event")}
end end
end end
@spec check_anonymous_participation(String.t(), String.t()) ::
{:ok, Event.t()} | {:error, String.t()}
defp check_anonymous_participation(actor_id, event_id) do
cond do
Config.anonymous_participation?() == false ->
{:error, dgettext("errors", "Anonymous participation is not enabled")}
to_string(Config.anonymous_actor_id()) != actor_id ->
{:error, dgettext("errors", "The anonymous actor ID is invalid")}
true ->
case Mobilizon.Events.get_event_with_preload(event_id) do
{:ok, %Event{} = event} ->
{:ok, event}
{:error, :event_not_found} ->
{:error,
dgettext("errors", "Event with this ID %{id} doesn't exist", id: inspect(event_id))}
end
end
end
@doc """ @doc """
Leave an event for an anonymous actor Leave an event for an anonymous actor
""" """
@ -141,25 +163,15 @@ defmodule Mobilizon.GraphQL.Resolvers.Participant do
_resolution _resolution
) )
when not is_nil(token) do when not is_nil(token) do
with {:anonymous_participation_enabled, true} <- case check_anonymous_participation(actor_id, event_id) do
{:anonymous_participation_enabled, Config.anonymous_participation?()}, {:ok, %Event{} = event} ->
{:anonymous_actor_id, true} <- %Actor{} = actor = Actors.get_actor_with_preload!(actor_id)
{:anonymous_actor_id, to_string(Config.anonymous_actor_id()) == actor_id},
{:has_event, {:ok, %Event{} = event}} <- case Participations.leave(event, actor, %{local: false, cancellation_token: token}) do
{:has_event, Mobilizon.Events.get_event_with_preload(event_id)}, {:ok, _activity, %Participant{id: participant_id} = _participant} ->
%Actor{} = actor <- Actors.get_actor_with_preload(actor_id),
{:ok, _activity, %Participant{id: participant_id} = _participant} <-
Participations.leave(event, actor, %{local: false, cancellation_token: token}) do
{:ok, %{event: %{id: event_id}, actor: %{id: actor_id}, id: participant_id}} {:ok, %{event: %{id: event_id}, actor: %{id: actor_id}, id: participant_id}}
else
{:has_event, _} ->
{:error,
dgettext("errors", "Event with this ID %{id} doesn't exist", id: inspect(event_id))}
{:is_owned, nil} -> {:error, :is_only_organizer} ->
{:error, dgettext("errors", "Profile is not owned by authenticated user")}
{:only_organizer, true} ->
{:error, {:error,
dgettext( dgettext(
"errors", "errors",
@ -168,6 +180,10 @@ defmodule Mobilizon.GraphQL.Resolvers.Participant do
{:error, :participant_not_found} -> {:error, :participant_not_found} ->
{:error, dgettext("errors", "Participant not found")} {:error, dgettext("errors", "Participant not found")}
{:error, _err} ->
{:error, dgettext("errors", "Failed to leave the event")}
end
end end
end end
@ -188,7 +204,7 @@ defmodule Mobilizon.GraphQL.Resolvers.Participant do
{:is_owned, nil} -> {:is_owned, nil} ->
{:error, dgettext("errors", "Profile is not owned by authenticated user")} {:error, dgettext("errors", "Profile is not owned by authenticated user")}
{:only_organizer, true} -> {:error, :is_only_organizer} ->
{:error, {:error,
dgettext( dgettext(
"errors", "errors",

View File

@ -31,7 +31,10 @@ defmodule Mobilizon.GraphQL.Resolvers.User do
@doc """ @doc """
Return current logged-in user Return current logged-in user
""" """
def get_current_user(_parent, _args, %{context: %{current_user: %User{} = user}}) do @spec get_current_user(any, map(), Absinthe.Resolution.t()) ::
{:error, :unauthenticated} | {:ok, Mobilizon.Users.User.t()}
def get_current_user(_parent, _args, %{context: %{current_user: %User{} = user} = context}) do
# Logger.error(inspect(context))
{:ok, user} {:ok, user}
end end
@ -199,7 +202,7 @@ defmodule Mobilizon.GraphQL.Resolvers.User do
@doc """ @doc """
Validate an user, get its actor and a token Validate an user, get its actor and a token
""" """
@spec validate_user(map(), %{token: String.t()}, map()) :: {:ok, map()} @spec validate_user(map(), %{token: String.t()}, map()) :: {:ok, map()} | {:error, String.t()}
def validate_user(_parent, %{token: token}, _resolution) do def validate_user(_parent, %{token: token}, _resolution) do
with {:check_confirmation_token, {:ok, %User{} = user}} <- with {:check_confirmation_token, {:ok, %User{} = user}} <-
{:check_confirmation_token, Email.User.check_confirmation_token(token)}, {:check_confirmation_token, Email.User.check_confirmation_token(token)},

View File

@ -94,7 +94,7 @@ defmodule Mix.Tasks.Mobilizon.Actors.New do
{:admin, nil} -> {:admin, nil} ->
shell_error("Profile with username #{Keyword.get(options, :group_admin)} wasn't found") shell_error("Profile with username #{Keyword.get(options, :group_admin)} wasn't found")
{:error, :insert_group, %Ecto.Changeset{errors: errors}, _} -> {:error, %Ecto.Changeset{errors: errors}} ->
shell_error(inspect(errors)) shell_error(inspect(errors))
shell_error("Error while creating group because of the above reason") shell_error("Error while creating group because of the above reason")
end end

View File

@ -50,6 +50,8 @@ defmodule Mix.Tasks.Mobilizon.Actors.Utils do
new_person new_person
end end
@spec create_group(Actor.t(), String.t(), String.t(), Keyword.t()) ::
{:ok, Actor.t()} | {:error, Ecto.Changeset.t()}
def create_group(%Actor{id: admin_id}, username, name, _options \\ []) do def create_group(%Actor{id: admin_id}, username, name, _options \\ []) do
{username, name} = username_and_name(username, name) {username, name} = username_and_name(username, name)

View File

@ -10,7 +10,7 @@ defmodule Mix.Tasks.Mobilizon.Ecto do
@doc """ @doc """
Ensures the given repository's migrations path exists on the file system. Ensures the given repository's migrations path exists on the file system.
""" """
@spec ensure_migrations_path(Ecto.Repo.t(), Keyword.t()) :: String.t() @spec ensure_migrations_path(Ecto.Repo.t(), Keyword.t()) :: String.t() | no_return
def ensure_migrations_path(repo, opts) do def ensure_migrations_path(repo, opts) do
path = opts[:migrations_path] || Path.join(source_repo_priv(repo), "migrations") path = opts[:migrations_path] || Path.join(source_repo_priv(repo), "migrations")
@ -39,6 +39,7 @@ defmodule Mix.Tasks.Mobilizon.Ecto do
Path.join(Application.app_dir(:mobilizon), priv) Path.join(Application.app_dir(:mobilizon), priv)
end end
@spec raise_missing_migrations(String.t(), Ecto.Repo.t()) :: no_return
defp raise_missing_migrations(path, repo) do defp raise_missing_migrations(path, repo) do
raise(""" raise("""
Could not find migrations directory #{inspect(path)} Could not find migrations directory #{inspect(path)}

View File

@ -71,7 +71,7 @@ defmodule Mix.Tasks.Mobilizon.Users.Clean do
end) end)
end end
@spec result(boolean(), boolean()) :: :ok @spec result(boolean(), non_neg_integer()) :: :ok
defp result(dry_run, nb_deleted_users) do defp result(dry_run, nb_deleted_users) do
if dry_run do if dry_run do
shell_info("#{nb_deleted_users} users would have been deleted") shell_info("#{nb_deleted_users} users would have been deleted")

View File

@ -15,7 +15,8 @@ defmodule Mobilizon.Activities.Activity do
:message, :message,
:message_params, :message_params,
:object_type, :object_type,
:object_id :object_id,
:object
] ]
@attrs @required_attrs ++ @optional_attrs @attrs @required_attrs ++ @optional_attrs
@ -28,6 +29,7 @@ defmodule Mobilizon.Activities.Activity do
message_params: map(), message_params: map(),
object_type: ObjectType.t(), object_type: ObjectType.t(),
object_id: String.t(), object_id: String.t(),
object: map(),
author: Actor.t(), author: Actor.t(),
group: Actor.t() group: Actor.t()
} }
@ -41,12 +43,14 @@ defmodule Mobilizon.Activities.Activity do
field(:message_params, :map, default: %{}) field(:message_params, :map, default: %{})
field(:object_type, ObjectType) field(:object_type, ObjectType)
field(:object_id, :string) field(:object_id, :string)
field(:object, :map, virtual: true)
field(:inserted_at, :utc_datetime) field(:inserted_at, :utc_datetime)
belongs_to(:author, Actor) belongs_to(:author, Actor)
belongs_to(:group, Actor) belongs_to(:group, Actor)
end end
@doc false @doc false
@spec changeset(t | Ecto.Schema.t(), map) :: Ecto.Changeset.t()
def changeset(activity, attrs) do def changeset(activity, attrs) do
activity activity
|> cast(attrs, @attrs) |> cast(attrs, @attrs)

View File

@ -11,7 +11,7 @@ defmodule Mobilizon.Actors.Actor do
alias Mobilizon.Actors.{ActorOpenness, ActorType, ActorVisibility, Follower, Member} alias Mobilizon.Actors.{ActorOpenness, ActorType, ActorVisibility, Follower, Member}
alias Mobilizon.Addresses.Address alias Mobilizon.Addresses.Address
alias Mobilizon.Discussions.Comment alias Mobilizon.Discussions.Comment
alias Mobilizon.Events.{Event, FeedToken} alias Mobilizon.Events.{Event, FeedToken, Participant}
alias Mobilizon.Medias.File alias Mobilizon.Medias.File
alias Mobilizon.Reports.{Note, Report} alias Mobilizon.Reports.{Note, Report}
alias Mobilizon.Users.User alias Mobilizon.Users.User
@ -33,8 +33,8 @@ defmodule Mobilizon.Actors.Actor do
posts_url: String.t(), posts_url: String.t(),
events_url: String.t(), events_url: String.t(),
type: ActorType.t(), type: ActorType.t(),
name: String.t(), name: String.t() | nil,
domain: String.t(), domain: String.t() | nil,
summary: String.t(), summary: String.t(),
preferred_username: String.t(), preferred_username: String.t(),
keys: String.t(), keys: String.t(),
@ -42,12 +42,13 @@ defmodule Mobilizon.Actors.Actor do
openness: ActorOpenness.t(), openness: ActorOpenness.t(),
visibility: ActorVisibility.t(), visibility: ActorVisibility.t(),
suspended: boolean, suspended: boolean,
avatar: File.t(), avatar: File.t() | nil,
banner: File.t(), banner: File.t() | nil,
user: User.t(), user: User.t(),
followers: [Follower.t()], followers: [Follower.t()],
followings: [Follower.t()], followings: [Follower.t()],
organized_events: [Event.t()], organized_events: [Event.t()],
participations: [Participant.t()],
comments: [Comment.t()], comments: [Comment.t()],
feed_tokens: [FeedToken.t()], feed_tokens: [FeedToken.t()],
created_reports: [Report.t()], created_reports: [Report.t()],
@ -184,6 +185,7 @@ defmodule Mobilizon.Actors.Actor do
has_many(:created_reports, Report, foreign_key: :reporter_id) has_many(:created_reports, Report, foreign_key: :reporter_id)
has_many(:subject_reports, Report, foreign_key: :reported_id) has_many(:subject_reports, Report, foreign_key: :reported_id)
has_many(:report_notes, Note, foreign_key: :moderator_id) has_many(:report_notes, Note, foreign_key: :moderator_id)
has_many(:participations, Participant, foreign_key: :actor_id)
has_many(:mentions, Mention) has_many(:mentions, Mention)
has_many(:shares, Share, foreign_key: :actor_id) has_many(:shares, Share, foreign_key: :actor_id)
has_many(:owner_shares, Share, foreign_key: :owner_actor_id) has_many(:owner_shares, Share, foreign_key: :owner_actor_id)
@ -243,7 +245,7 @@ defmodule Mobilizon.Actors.Actor do
end end
@doc false @doc false
@spec changeset(t, map) :: Ecto.Changeset.t() @spec changeset(t | Ecto.Schema.t(), map) :: Ecto.Changeset.t()
def changeset(%__MODULE__{} = actor, attrs) do def changeset(%__MODULE__{} = actor, attrs) do
actor actor
|> cast(attrs, @attrs) |> cast(attrs, @attrs)
@ -278,7 +280,7 @@ defmodule Mobilizon.Actors.Actor do
@doc """ @doc """
Changeset for person registration. Changeset for person registration.
""" """
@spec registration_changeset(t, map) :: Ecto.Changeset.t() @spec registration_changeset(t | Ecto.Schema.t(), map) :: Ecto.Changeset.t()
def registration_changeset(%__MODULE__{} = actor, attrs) do def registration_changeset(%__MODULE__{} = actor, attrs) do
actor actor
|> cast(attrs, @registration_attrs) |> cast(attrs, @registration_attrs)
@ -293,7 +295,6 @@ defmodule Mobilizon.Actors.Actor do
""" """
@spec remote_actor_creation_changeset(map) :: Ecto.Changeset.t() @spec remote_actor_creation_changeset(map) :: Ecto.Changeset.t()
def remote_actor_creation_changeset(attrs) do def remote_actor_creation_changeset(attrs) do
changeset =
%__MODULE__{} %__MODULE__{}
|> cast(attrs, @remote_actor_creation_attrs) |> cast(attrs, @remote_actor_creation_attrs)
|> validate_required(@remote_actor_creation_required_attrs) |> validate_required(@remote_actor_creation_required_attrs)
@ -302,10 +303,6 @@ defmodule Mobilizon.Actors.Actor do
|> validate_required(:domain) |> validate_required(:domain)
|> validate_length(:summary, max: 5000) |> validate_length(:summary, max: 5000)
|> validate_length(:preferred_username, max: 100) |> validate_length(:preferred_username, max: 100)
Logger.debug("Remote actor creation: #{inspect(changeset)}")
changeset
end end
@spec common_changeset(Ecto.Changeset.t(), map()) :: Ecto.Changeset.t() @spec common_changeset(Ecto.Changeset.t(), map()) :: Ecto.Changeset.t()
@ -323,7 +320,7 @@ defmodule Mobilizon.Actors.Actor do
@doc """ @doc """
Changeset for group creation Changeset for group creation
""" """
@spec group_creation_changeset(t, map) :: Ecto.Changeset.t() @spec group_creation_changeset(t | Ecto.Schema.t(), map) :: Ecto.Changeset.t()
def group_creation_changeset(actor, params) do def group_creation_changeset(actor, params) do
actor actor
|> cast(params, @group_creation_attrs) |> cast(params, @group_creation_attrs)
@ -416,12 +413,8 @@ defmodule Mobilizon.Actors.Actor do
@spec build_relay_creation_attrs :: Ecto.Changeset.t() @spec build_relay_creation_attrs :: Ecto.Changeset.t()
def build_relay_creation_attrs do def build_relay_creation_attrs do
data = %{ data = %{
name: Config.get([:instance, :name], "Mobilizon"), name: Config.instance_name(),
summary: summary: Config.instance_description(),
Config.get(
[:instance, :description],
"An internal service actor for this Mobilizon instance"
),
keys: Crypto.generate_rsa_2048_private_key(), keys: Crypto.generate_rsa_2048_private_key(),
preferred_username: "relay", preferred_username: "relay",
domain: nil, domain: nil,

View File

@ -75,13 +75,20 @@ defmodule Mobilizon.Actors do
@doc """ @doc """
Gets an actor with preloaded relations. Gets an actor with preloaded relations.
""" """
@spec get_actor_with_preload(integer | String.t()) :: Actor.t() | nil @spec get_actor_with_preload(integer | String.t(), boolean) :: Actor.t() | nil
def get_actor_with_preload(id, include_suspended \\ false) do def get_actor_with_preload(id, include_suspended \\ false) do
id id
|> actor_with_preload_query(include_suspended) |> actor_with_preload_query(include_suspended)
|> Repo.one() |> Repo.one()
end end
@spec get_actor_with_preload!(integer | String.t(), boolean) :: Actor.t()
def get_actor_with_preload!(id, include_suspended \\ false) do
id
|> actor_with_preload_query(include_suspended)
|> Repo.one!()
end
@doc """ @doc """
Gets a local actor with preloaded relations. Gets a local actor with preloaded relations.
""" """
@ -148,9 +155,7 @@ defmodule Mobilizon.Actors do
""" """
@spec get_actor_by_name(String.t(), ActorType.t() | nil) :: Actor.t() | nil @spec get_actor_by_name(String.t(), ActorType.t() | nil) :: Actor.t() | nil
def get_actor_by_name(name, type \\ nil) do def get_actor_by_name(name, type \\ nil) do
query = from(a in Actor) Actor
query
|> filter_by_type(type) |> filter_by_type(type)
|> filter_by_name(name |> String.trim() |> String.trim_leading("@") |> String.split("@")) |> filter_by_name(name |> String.trim() |> String.trim_leading("@") |> String.split("@"))
|> Repo.one() |> Repo.one()
@ -161,9 +166,7 @@ defmodule Mobilizon.Actors do
""" """
@spec get_local_actor_by_name(String.t()) :: Actor.t() | nil @spec get_local_actor_by_name(String.t()) :: Actor.t() | nil
def get_local_actor_by_name(name) do def get_local_actor_by_name(name) do
query = from(a in Actor) Actor
query
|> filter_by_name([name]) |> filter_by_name([name])
|> Repo.one() |> Repo.one()
end end
@ -210,7 +213,8 @@ defmodule Mobilizon.Actors do
@doc """ @doc """
Creates a new person actor. Creates a new person actor.
""" """
@spec new_person(map) :: {:ok, Actor.t()} | {:error, Ecto.Changeset.t()} @spec new_person(map, default_actor :: boolean()) ::
{:ok, Actor.t()} | {:error, Ecto.Changeset.t()}
def new_person(args, default_actor \\ false) do def new_person(args, default_actor \\ false) do
args = Map.put(args, :keys, Crypto.generate_rsa_2048_private_key()) args = Map.put(args, :keys, Crypto.generate_rsa_2048_private_key())
@ -323,8 +327,8 @@ defmodule Mobilizon.Actors do
String.t(), String.t(),
boolean, boolean,
boolean, boolean,
integer, integer | nil,
integer integer | nil
) :: Page.t() ) :: Page.t()
def list_actors( def list_actors(
type \\ :Person, type \\ :Person,
@ -367,7 +371,23 @@ defmodule Mobilizon.Actors do
|> Page.build_page(page, limit) |> Page.build_page(page, limit)
end end
@spec filter_actors(Ecto.Query.t(), String.t(), String.t(), String.t(), boolean(), boolean()) :: @spec list_suspended_actors_to_purge(Keyword.t()) :: list(Actors.t())
def list_suspended_actors_to_purge(options) do
suspension_days = Keyword.get(options, :suspension, 30)
Actor
|> filter_suspended_days(suspension_days)
|> Repo.all()
end
@spec filter_actors(
Ecto.Queryable.t(),
String.t(),
String.t(),
String.t(),
boolean(),
boolean()
) ::
Ecto.Query.t() Ecto.Query.t()
defp filter_actors( defp filter_actors(
query, query,
@ -403,14 +423,27 @@ defmodule Mobilizon.Actors do
defp filter_remote(query, true), do: filter_local(query) defp filter_remote(query, true), do: filter_local(query)
defp filter_remote(query, false), do: filter_external(query) defp filter_remote(query, false), do: filter_external(query)
@spec filter_suspended(Ecto.Query.t(), boolean()) :: Ecto.Query.t() @spec filter_suspended(Ecto.Queryable.t(), boolean()) :: Ecto.Query.t()
defp filter_suspended(query, true), do: where(query, [a], a.suspended) defp filter_suspended(query, true), do: where(query, [a], a.suspended)
defp filter_suspended(query, false), do: where(query, [a], not a.suspended) defp filter_suspended(query, false), do: where(query, [a], not a.suspended)
@spec filter_out_anonymous_actor_id(Ecto.Query.t(), integer() | String.t()) :: Ecto.Query.t() @spec filter_out_anonymous_actor_id(Ecto.Queryable.t(), integer() | String.t()) ::
Ecto.Query.t()
defp filter_out_anonymous_actor_id(query, anonymous_actor_id), defp filter_out_anonymous_actor_id(query, anonymous_actor_id),
do: where(query, [a], a.id != ^anonymous_actor_id) do: where(query, [a], a.id != ^anonymous_actor_id)
@spec filter_suspended_days(Ecto.Queryable.t(), integer()) :: Ecto.Query.t()
defp filter_suspended_days(query, suspended_days) do
expiration_date = DateTime.add(DateTime.utc_now(), suspended_days * 24 * -3600)
where(
query,
[a],
a.suspended and
a.updated_at > ^expiration_date
)
end
@doc """ @doc """
Returns the list of local actors by their username. Returns the list of local actors by their username.
""" """
@ -486,14 +519,14 @@ defmodule Mobilizon.Actors do
end end
end end
@spec get_local_group_by_url(String.t()) :: Actor.t() @spec get_local_group_by_url(String.t()) :: Actor.t() | nil
def get_local_group_by_url(group_url) do def get_local_group_by_url(group_url) do
group_query() group_query()
|> where([q], q.url == ^group_url and is_nil(q.domain)) |> where([q], q.url == ^group_url and is_nil(q.domain))
|> Repo.one() |> Repo.one()
end end
@spec get_group_by_members_url(String.t()) :: Actor.t() @spec get_group_by_members_url(String.t()) :: Actor.t() | nil
def get_group_by_members_url(members_url) do def get_group_by_members_url(members_url) do
group_query() group_query()
|> where([q], q.members_url == ^members_url) |> where([q], q.members_url == ^members_url)
@ -531,7 +564,7 @@ defmodule Mobilizon.Actors do
{:ok, %{insert_group: %Actor{} = group, add_admin_member: %Member{} = _admin_member}} -> {:ok, %{insert_group: %Actor{} = group, add_admin_member: %Member{} = _admin_member}} ->
{:ok, group} {:ok, group}
{:error, %Ecto.Changeset{} = err} -> {:error, _err, %Ecto.Changeset{} = err, _} ->
{:error, err} {:error, err}
end end
else else
@ -606,7 +639,7 @@ defmodule Mobilizon.Actors do
@doc """ @doc """
Gets a single member. Gets a single member.
""" """
@spec get_member(integer | String.t()) :: {:ok, Member.t()} | nil @spec get_member(integer | String.t()) :: Member.t() | nil
def get_member(id) do def get_member(id) do
Member Member
|> Repo.get(id) |> Repo.get(id)
@ -623,7 +656,7 @@ defmodule Mobilizon.Actors do
@doc """ @doc """
Gets a single member of an actor (for example a group). Gets a single member of an actor (for example a group).
""" """
@spec get_member(integer | String.t(), integer | String.t()) :: @spec get_member(actor_id :: integer | String.t(), parent_id :: integer | String.t()) ::
{:ok, Member.t()} | {:error, :member_not_found} {:ok, Member.t()} | {:error, :member_not_found}
def get_member(actor_id, parent_id) do def get_member(actor_id, parent_id) do
case Repo.get_by(Member, actor_id: actor_id, parent_id: parent_id) do case Repo.get_by(Member, actor_id: actor_id, parent_id: parent_id) do
@ -1190,12 +1223,23 @@ defmodule Mobilizon.Actors do
@doc """ @doc """
Makes an actor following another actor. Makes an actor following another actor.
""" """
@spec follow(Actor.t(), Actor.t(), String.t() | nil, boolean | nil) :: @spec follow(
{:ok, Follower.t()} | {:error, atom, String.t()} followed :: Actor.t(),
follower :: Actor.t(),
url :: String.t() | nil,
approved :: boolean | nil
) ::
{:ok, Follower.t()}
| {:error, :already_following | :followed_suspended | Ecto.Changeset.t()}
def follow(%Actor{} = followed, %Actor{} = follower, url \\ nil, approved \\ true) do def follow(%Actor{} = followed, %Actor{} = follower, url \\ nil, approved \\ true) do
with {:suspended, false} <- {:suspended, followed.suspended}, if followed.suspended do
# Check if followed has blocked follower {:error, :followed_suspended}
{:already_following, nil} <- {:already_following, is_following(follower, followed)} do else
case is_following(follower, followed) do
%Follower{} ->
{:error, :already_following}
nil ->
Logger.info( Logger.info(
"Making #{Actor.preferred_username_and_domain(follower)} follow #{Actor.preferred_username_and_domain(followed)} " <> "Making #{Actor.preferred_username_and_domain(follower)} follow #{Actor.preferred_username_and_domain(followed)} " <>
"(approved: #{approved})" "(approved: #{approved})"
@ -1207,14 +1251,7 @@ defmodule Mobilizon.Actors do
"approved" => approved, "approved" => approved,
"url" => url "url" => url
}) })
else end
{:already_following, %Follower{}} ->
{:error, :already_following,
"Could not follow actor: you are already following #{Actor.preferred_username_and_domain(followed)}"}
{:suspended, _} ->
{:error, :suspended,
"Could not follow actor: #{Actor.preferred_username_and_domain(followed)} has been suspended"}
end end
end end
@ -1331,7 +1368,7 @@ defmodule Mobilizon.Actors do
) )
end end
@spec actor_by_username_or_name_query(Ecto.Query.t(), String.t()) :: Ecto.Query.t() @spec actor_by_username_or_name_query(Ecto.Queryable.t(), String.t()) :: Ecto.Query.t()
defp actor_by_username_or_name_query(query, ""), do: query defp actor_by_username_or_name_query(query, ""), do: query
defp actor_by_username_or_name_query(query, username) do defp actor_by_username_or_name_query(query, username) do
@ -1358,7 +1395,7 @@ defmodule Mobilizon.Actors do
) )
end end
@spec actors_for_location(Ecto.Query.t(), String.t(), integer()) :: Ecto.Query.t() @spec actors_for_location(Ecto.Queryable.t(), String.t(), integer()) :: Ecto.Query.t()
defp actors_for_location(query, location, radius) defp actors_for_location(query, location, radius)
when is_valid_string(location) and not is_nil(radius) do when is_valid_string(location) and not is_nil(radius) do
with {lon, lat} <- Geohax.decode(location), with {lon, lat} <- Geohax.decode(location),
@ -1474,7 +1511,7 @@ defmodule Mobilizon.Actors do
|> select([m, _a], m) |> select([m, _a], m)
end end
@spec filter_member_role(Ecto.Query.t(), list(atom()) | atom()) :: Ecto.Query.t() @spec filter_member_role(Ecto.Queryable.t(), list(atom()) | atom()) :: Ecto.Query.t()
defp filter_member_role(query, []), do: query defp filter_member_role(query, []), do: query
defp filter_member_role(query, roles) when is_list(roles) do defp filter_member_role(query, roles) when is_list(roles) do
@ -1597,24 +1634,24 @@ defmodule Mobilizon.Actors do
|> order_by(desc: :updated_at) |> order_by(desc: :updated_at)
end end
@spec filter_local(Ecto.Query.t()) :: Ecto.Query.t() @spec filter_local(Ecto.Queryable.t()) :: Ecto.Query.t()
defp filter_local(query) do defp filter_local(query) do
from(a in query, where: is_nil(a.domain)) from(a in query, where: is_nil(a.domain))
end end
@spec filter_external(Ecto.Query.t()) :: Ecto.Query.t() @spec filter_external(Ecto.Queryable.t()) :: Ecto.Query.t()
defp filter_external(query) do defp filter_external(query) do
from(a in query, where: not is_nil(a.domain)) from(a in query, where: not is_nil(a.domain))
end end
@spec filter_follower_actors_external(Ecto.Query.t()) :: Ecto.Query.t() @spec filter_follower_actors_external(Ecto.Queryable.t()) :: Ecto.Query.t()
defp filter_follower_actors_external(query) do defp filter_follower_actors_external(query) do
query query
|> where([_f, a], not is_nil(a.domain)) |> where([_f, a], not is_nil(a.domain))
|> preload([f, a], [:target_actor, :actor]) |> preload([f, a], [:target_actor, :actor])
end end
@spec filter_by_type(Ecto.Query.t(), ActorType.t()) :: Ecto.Query.t() @spec filter_by_type(Ecto.Queryable.t(), ActorType.t() | nil) :: Ecto.Queryable.t()
defp filter_by_type(query, type) defp filter_by_type(query, type)
when type in [:Person, :Group, :Application, :Service, :Organisation] do when type in [:Person, :Group, :Application, :Service, :Organisation] do
from(a in query, where: a.type == ^type) from(a in query, where: a.type == ^type)
@ -1622,12 +1659,12 @@ defmodule Mobilizon.Actors do
defp filter_by_type(query, _type), do: query defp filter_by_type(query, _type), do: query
@spec filter_by_types(Ecto.Query.t(), [ActorType.t()]) :: Ecto.Query.t() @spec filter_by_types(Ecto.Queryable.t(), [ActorType.t()]) :: Ecto.Query.t()
defp filter_by_types(query, types) do defp filter_by_types(query, types) do
from(a in query, where: a.type in ^types) from(a in query, where: a.type in ^types)
end end
@spec filter_by_minimum_visibility(Ecto.Query.t(), atom()) :: Ecto.Query.t() @spec filter_by_minimum_visibility(Ecto.Queryable.t(), atom()) :: Ecto.Query.t()
defp filter_by_minimum_visibility(query, :private), do: query defp filter_by_minimum_visibility(query, :private), do: query
defp filter_by_minimum_visibility(query, :restricted) do defp filter_by_minimum_visibility(query, :restricted) do
@ -1642,7 +1679,7 @@ defmodule Mobilizon.Actors do
from(a in query, where: a.visibility == ^:public) from(a in query, where: a.visibility == ^:public)
end end
@spec filter_by_name(query :: Ecto.Query.t(), [String.t()]) :: Ecto.Query.t() @spec filter_by_name(query :: Ecto.Queryable.t(), [String.t()]) :: Ecto.Query.t()
defp filter_by_name(query, [name]) do defp filter_by_name(query, [name]) do
where(query, [a], a.preferred_username == ^name and is_nil(a.domain)) where(query, [a], a.preferred_username == ^name and is_nil(a.domain))
end end
@ -1655,7 +1692,7 @@ defmodule Mobilizon.Actors do
end end
end end
@spec filter_followed_by_approved_status(Ecto.Query.t(), boolean() | nil) :: Ecto.Query.t() @spec filter_followed_by_approved_status(Ecto.Queryable.t(), boolean() | nil) :: Ecto.Query.t()
defp filter_followed_by_approved_status(query, nil), do: query defp filter_followed_by_approved_status(query, nil), do: query
defp filter_followed_by_approved_status(query, approved) do defp filter_followed_by_approved_status(query, approved) do

View File

@ -32,7 +32,7 @@ defmodule Mobilizon.Actors.Bot do
end end
@doc false @doc false
@spec changeset(t, map) :: Ecto.Changeset.t() @spec changeset(t | Ecto.Schema.t(), map) :: Ecto.Changeset.t()
def changeset(%__MODULE__{} = bot, attrs) do def changeset(%__MODULE__{} = bot, attrs) do
bot bot
|> cast(attrs, @attrs) |> cast(attrs, @attrs)

View File

@ -38,7 +38,7 @@ defmodule Mobilizon.Actors.Follower do
end end
@doc false @doc false
@spec changeset(follower :: t, attrs :: map) :: Ecto.Changeset.t() @spec changeset(follower :: t | Ecto.Schema.t(), attrs :: map) :: Ecto.Changeset.t()
def changeset(follower, attrs) do def changeset(follower, attrs) do
follower follower
|> cast(attrs, @attrs) |> cast(attrs, @attrs)

View File

@ -59,7 +59,7 @@ defmodule Mobilizon.Actors.Member do
def is_administrator(%__MODULE__{}), do: false def is_administrator(%__MODULE__{}), do: false
@doc false @doc false
@spec changeset(t, map) :: Ecto.Changeset.t() @spec changeset(t | Ecto.Schema.t(), map) :: Ecto.Changeset.t()
def changeset(%__MODULE__{} = member, attrs) do def changeset(%__MODULE__{} = member, attrs) do
member member
|> cast(attrs, @attrs) |> cast(attrs, @attrs)

View File

@ -57,7 +57,7 @@ defmodule Mobilizon.Addresses.Address do
end end
@doc false @doc false
@spec changeset(t, map) :: Ecto.Changeset.t() @spec changeset(t | Ecto.Schema.t(), map) :: Ecto.Changeset.t()
def changeset(%__MODULE__{} = address, attrs) do def changeset(%__MODULE__{} = address, attrs) do
address address
|> cast(attrs, @attrs) |> cast(attrs, @attrs)

View File

@ -118,7 +118,7 @@ defmodule Mobilizon.Addresses do
) )
end end
@spec order_by_coords(Ecto.Query.t(), map | nil) :: Ecto.Query.t() @spec order_by_coords(Ecto.Queryable.t(), map | nil) :: Ecto.Query.t()
defp order_by_coords(query, nil), do: query defp order_by_coords(query, nil), do: query
defp order_by_coords(query, coords) do defp order_by_coords(query, coords) do
@ -128,7 +128,7 @@ defmodule Mobilizon.Addresses do
) )
end end
@spec filter_by_contry(Ecto.Query.t(), String.t() | nil) :: Ecto.Query.t() @spec filter_by_contry(Ecto.Queryable.t(), String.t() | nil) :: Ecto.Query.t()
defp filter_by_contry(query, nil), do: query defp filter_by_contry(query, nil), do: query
defp filter_by_contry(query, country) do defp filter_by_contry(query, country) do

View File

@ -35,7 +35,7 @@ defmodule Mobilizon.Admin.ActionLog do
end end
@doc false @doc false
@spec changeset(t, map) :: Ecto.Changeset.t() @spec changeset(t | Ecto.Schema.t(), map) :: Ecto.Changeset.t()
def changeset(%__MODULE__{} = action_log, attrs) do def changeset(%__MODULE__{} = action_log, attrs) do
action_log action_log
|> cast(attrs, @attrs) |> cast(attrs, @attrs)

View File

@ -45,7 +45,8 @@ defmodule Mobilizon.Admin do
@doc """ @doc """
Log an admin action Log an admin action
""" """
@spec log_action(Actor.t(), String.t(), String.t()) :: {:ok, ActionLog.t()} @spec log_action(Actor.t(), String.t(), struct()) ::
{:ok, ActionLog.t()} | {:error, Ecto.Changeset.t() | :user_not_moderator}
def log_action(%Actor{user_id: user_id, id: actor_id}, action, target) do def log_action(%Actor{user_id: user_id, id: actor_id}, action, target) do
with %User{role: role} <- Users.get_user!(user_id), with %User{role: role} <- Users.get_user!(user_id),
{:role, true} <- {:role, role in [:administrator, :moderator]}, {:role, true} <- {:role, role in [:administrator, :moderator]},
@ -58,6 +59,9 @@ defmodule Mobilizon.Admin do
"changes" => stringify_struct(target) "changes" => stringify_struct(target)
}) do }) do
{:ok, create_action_log} {:ok, create_action_log}
else
{:role, false} ->
{:error, :user_not_moderator}
end end
end end
@ -109,12 +113,7 @@ defmodule Mobilizon.Admin do
end end
end end
def set_admin_setting_value(group, name, value) do @spec save_settings(String.t(), map()) :: {:ok, any} | {:error, any}
Setting
|> Setting.changeset(%{group: group, name: name, value: value})
|> Repo.insert(on_conflict: :replace_all, conflict_target: [:group, :name])
end
def save_settings(group, args) do def save_settings(group, args) do
Multi.new() Multi.new()
|> do_save_setting(group, args) |> do_save_setting(group, args)
@ -125,6 +124,7 @@ defmodule Mobilizon.Admin do
Setting |> where([s], s.group == ^group) |> Repo.delete_all() Setting |> where([s], s.group == ^group) |> Repo.delete_all()
end end
@spec do_save_setting(Ecto.Multi.t(), String.t(), map()) :: Ecto.Multi.t()
defp do_save_setting(transaction, _group, args) when args == %{}, do: transaction defp do_save_setting(transaction, _group, args) when args == %{}, do: transaction
defp do_save_setting(transaction, group, args) do defp do_save_setting(transaction, group, args) do
@ -147,6 +147,7 @@ defmodule Mobilizon.Admin do
do_save_setting(transaction, group, rest) do_save_setting(transaction, group, rest)
end end
@spec convert_to_string(any()) :: String.t()
defp convert_to_string(val) do defp convert_to_string(val) do
case val do case val do
val when is_list(val) -> Jason.encode!(val) val when is_list(val) -> Jason.encode!(val)

View File

@ -9,6 +9,12 @@ defmodule Mobilizon.Admin.Setting do
@optional_attrs [:value] @optional_attrs [:value]
@attrs @required_attrs ++ @optional_attrs @attrs @required_attrs ++ @optional_attrs
@type t :: %{
group: String.t(),
name: String.t(),
value: String.t()
}
schema "admin_settings" do schema "admin_settings" do
field(:group, :string) field(:group, :string)
field(:name, :string) field(:name, :string)
@ -18,6 +24,7 @@ defmodule Mobilizon.Admin.Setting do
end end
@doc false @doc false
@spec changeset(t | Ecto.Schema.t(), map) :: Ecto.Changeset.t()
def changeset(setting, attrs) do def changeset(setting, attrs) do
setting setting
|> cast(attrs, @attrs) |> cast(attrs, @attrs)

View File

@ -7,7 +7,24 @@ defmodule Mobilizon.Config do
alias Mobilizon.Service.GitStatus alias Mobilizon.Service.GitStatus
require Logger require Logger
@spec instance_config :: keyword @type mobilizon_config :: [
name: String.t(),
description: String.t(),
hostname: String.t(),
registrations_open: boolean(),
languages: list(String.t()),
default_language: String.t(),
registration_email_allowlist: list(String.t()),
registration_email_denylist: list(String.t()),
demo: boolean(),
repository: String.t(),
email_from: String.t(),
email_reply_to: String.t(),
federating: boolean(),
remove_orphan_uploads: boolean()
]
@spec instance_config :: mobilizon_config
def instance_config, do: Application.get_env(:mobilizon, :instance) def instance_config, do: Application.get_env(:mobilizon, :instance)
@spec instance_name :: String.t() @spec instance_name :: String.t()
@ -139,10 +156,10 @@ defmodule Mobilizon.Config do
def instance_user_agent, def instance_user_agent,
do: "#{instance_hostname()} - Mobilizon #{instance_version()}" do: "#{instance_hostname()} - Mobilizon #{instance_version()}"
@spec instance_federating :: String.t() @spec instance_federating :: boolean()
def instance_federating, do: instance_config()[:federating] def instance_federating, do: instance_config()[:federating]
@spec instance_geocoding_provider :: atom() @spec instance_geocoding_provider :: module()
def instance_geocoding_provider, def instance_geocoding_provider,
do: get_in(Application.get_env(:mobilizon, Mobilizon.Service.Geospatial), [:service]) do: get_in(Application.get_env(:mobilizon, Mobilizon.Service.Geospatial), [:service])
@ -150,63 +167,90 @@ defmodule Mobilizon.Config do
def instance_geocoding_autocomplete, def instance_geocoding_autocomplete,
do: instance_geocoding_provider() !== Mobilizon.Service.Geospatial.Nominatim do: instance_geocoding_provider() !== Mobilizon.Service.Geospatial.Nominatim
@spec maps_config :: [
tiles: [endpoint: String.t(), attribution: String.t()],
rounting: [type: atom]
]
defp maps_config, do: Application.get_env(:mobilizon, :maps)
@spec instance_maps_tiles_endpoint :: String.t() @spec instance_maps_tiles_endpoint :: String.t()
def instance_maps_tiles_endpoint, do: Application.get_env(:mobilizon, :maps)[:tiles][:endpoint] def instance_maps_tiles_endpoint, do: maps_config()[:tiles][:endpoint]
@spec instance_maps_tiles_attribution :: String.t() @spec instance_maps_tiles_attribution :: String.t()
def instance_maps_tiles_attribution, def instance_maps_tiles_attribution,
do: Application.get_env(:mobilizon, :maps)[:tiles][:attribution] do: maps_config()[:tiles][:attribution]
@spec instance_maps_routing_type :: atom() @spec instance_maps_routing_type :: atom()
def instance_maps_routing_type, def instance_maps_routing_type,
do: Application.get_env(:mobilizon, :maps)[:routing][:type] do: maps_config()[:routing][:type]
@typep anonymous_config_type :: [
participation: [
allowed: boolean,
validation: [
email: [enabled: boolean(), confirmation_required: boolean()],
captcha: [enabled: boolean()]
]
],
event_creation: [
allowed: boolean,
validation: [
email: [enabled: boolean(), confirmation_required: boolean()],
captcha: [enabled: boolean()]
]
],
reports: [
allowed: boolean()
]
]
@spec anonymous_config :: anonymous_config_type
defp anonymous_config, do: Application.get_env(:mobilizon, :anonymous)
@spec anonymous_participation? :: boolean @spec anonymous_participation? :: boolean
def anonymous_participation?, def anonymous_participation?,
do: Application.get_env(:mobilizon, :anonymous)[:participation][:allowed] do: anonymous_config()[:participation][:allowed]
@spec anonymous_participation_email_required? :: boolean @spec anonymous_participation_email_required? :: boolean
def anonymous_participation_email_required?, def anonymous_participation_email_required?,
do: Application.get_env(:mobilizon, :anonymous)[:participation][:validation][:email][:enabled] do: anonymous_config()[:participation][:validation][:email][:enabled]
@spec anonymous_participation_email_confirmation_required? :: boolean @spec anonymous_participation_email_confirmation_required? :: boolean
def anonymous_participation_email_confirmation_required?, def anonymous_participation_email_confirmation_required?,
do: do:
Application.get_env(:mobilizon, :anonymous)[:participation][:validation][:email][ anonymous_config()[:participation][:validation][:email][
:confirmation_required :confirmation_required
] ]
@spec anonymous_participation_email_captcha_required? :: boolean @spec anonymous_participation_email_captcha_required? :: boolean
def anonymous_participation_email_captcha_required?, def anonymous_participation_email_captcha_required?,
do: do: anonymous_config()[:participation][:validation][:captcha][:enabled]
Application.get_env(:mobilizon, :anonymous)[:participation][:validation][:captcha][:enabled]
@spec anonymous_event_creation? :: boolean @spec anonymous_event_creation? :: boolean
def anonymous_event_creation?, def anonymous_event_creation?,
do: Application.get_env(:mobilizon, :anonymous)[:event_creation][:allowed] do: anonymous_config()[:event_creation][:allowed]
@spec anonymous_event_creation_email_required? :: boolean @spec anonymous_event_creation_email_required? :: boolean
def anonymous_event_creation_email_required?, def anonymous_event_creation_email_required?,
do: do: anonymous_config()[:event_creation][:validation][:email][:enabled]
Application.get_env(:mobilizon, :anonymous)[:event_creation][:validation][:email][:enabled]
@spec anonymous_event_creation_email_confirmation_required? :: boolean @spec anonymous_event_creation_email_confirmation_required? :: boolean
def anonymous_event_creation_email_confirmation_required?, def anonymous_event_creation_email_confirmation_required?,
do: do:
Application.get_env(:mobilizon, :anonymous)[:event_creation][:validation][:email][ anonymous_config()[:event_creation][:validation][:email][
:confirmation_required :confirmation_required
] ]
@spec anonymous_event_creation_email_captcha_required? :: boolean @spec anonymous_event_creation_email_captcha_required? :: boolean
def anonymous_event_creation_email_captcha_required?, def anonymous_event_creation_email_captcha_required?,
do: do:
Application.get_env(:mobilizon, :anonymous)[:event_creation][:validation][:captcha][ anonymous_config()[:event_creation][:validation][:captcha][
:enabled :enabled
] ]
@spec anonymous_reporting? :: boolean @spec anonymous_reporting? :: boolean
def anonymous_reporting?, def anonymous_reporting?,
do: Application.get_env(:mobilizon, :anonymous)[:reports][:allowed] do: anonymous_config()[:reports][:allowed]
@spec oauth_consumer_strategies() :: list({atom(), String.t()}) @spec oauth_consumer_strategies() :: list({atom(), String.t()})
def oauth_consumer_strategies do def oauth_consumer_strategies do
@ -265,7 +309,7 @@ defmodule Mobilizon.Config do
@spec admin_settings :: map @spec admin_settings :: map
def admin_settings, do: get_cached_value(:admin_config) def admin_settings, do: get_cached_value(:admin_config)
@spec get(key :: module | atom) :: any @spec get(keys :: module | atom | [module | atom]) :: any
def get(key), do: get(key, nil) def get(key), do: get(key, nil)
@spec get(keys :: [module | atom], default :: any) :: any @spec get(keys :: [module | atom], default :: any) :: any
@ -281,7 +325,7 @@ defmodule Mobilizon.Config do
@spec get(key :: module | atom, default :: any) :: any @spec get(key :: module | atom, default :: any) :: any
def get(key, default), do: Application.get_env(:mobilizon, key, default) def get(key, default), do: Application.get_env(:mobilizon, key, default)
@spec get!(key :: module | atom) :: any @spec get!(key :: module | atom) :: any | no_return
def get!(key) do def get!(key) do
value = get(key, nil) value = get(key, nil)

View File

@ -87,7 +87,7 @@ defmodule Mobilizon.Discussions.Comment do
end end
@doc false @doc false
@spec changeset(t, map) :: Ecto.Changeset.t() @spec changeset(t | Ecto.Schema.t(), map) :: Ecto.Changeset.t()
def changeset(%__MODULE__{} = comment, attrs) do def changeset(%__MODULE__{} = comment, attrs) do
comment comment
|> common_changeset(attrs) |> common_changeset(attrs)

View File

@ -59,7 +59,7 @@ defmodule Mobilizon.Discussions.Discussion do
end end
@doc false @doc false
@spec changeset(t, map) :: Ecto.Changeset.t() @spec changeset(t | Ecto.Schema.t(), map) :: Ecto.Changeset.t()
def changeset(%__MODULE__{} = discussion, attrs) do def changeset(%__MODULE__{} = discussion, attrs) do
discussion discussion
|> cast(attrs, @attrs) |> cast(attrs, @attrs)

View File

@ -71,7 +71,7 @@ defmodule Mobilizon.Discussions do
We only get first comment of thread, and count replies. We only get first comment of thread, and count replies.
Read: https://hexdocs.pm/absinthe/ecto.html#dataloader Read: https://hexdocs.pm/absinthe/ecto.html#dataloader
""" """
@spec query(atom(), map()) :: Ecto.Queryable.t() @spec query(atom(), map()) :: Ecto.Query.t()
def query(Comment, %{top_level: true}) do def query(Comment, %{top_level: true}) do
Comment Comment
|> join(:left, [c], r in Comment, on: r.origin_comment_id == c.id) |> join(:left, [c], r in Comment, on: r.origin_comment_id == c.id)
@ -158,7 +158,7 @@ defmodule Mobilizon.Discussions do
Gets a comment by its URL, with all associations loaded. Gets a comment by its URL, with all associations loaded.
Raises `Ecto.NoResultsError` if the comment does not exist. Raises `Ecto.NoResultsError` if the comment does not exist.
""" """
@spec get_comment_from_url_with_preload(String.t()) :: Comment.t() @spec get_comment_from_url_with_preload!(String.t()) :: Comment.t()
def get_comment_from_url_with_preload!(url) do def get_comment_from_url_with_preload!(url) do
Comment Comment
|> Repo.get_by!(url: url) |> Repo.get_by!(url: url)
@ -168,7 +168,7 @@ defmodule Mobilizon.Discussions do
@doc """ @doc """
Gets a comment by its UUID, with all associations loaded. Gets a comment by its UUID, with all associations loaded.
""" """
@spec get_comment_from_uuid_with_preload(String.t()) :: Comment.t() @spec get_comment_from_uuid_with_preload(String.t()) :: Comment.t() | nil
def get_comment_from_uuid_with_preload(uuid) do def get_comment_from_uuid_with_preload(uuid) do
Comment Comment
|> Repo.get_by(uuid: uuid) |> Repo.get_by(uuid: uuid)
@ -355,7 +355,7 @@ defmodule Mobilizon.Discussions do
@doc """ @doc """
Get a discussion by it's slug Get a discussion by it's slug
""" """
@spec get_discussion_by_slug(String.t()) :: Discussion.t() @spec get_discussion_by_slug(String.t()) :: Discussion.t() | nil
def get_discussion_by_slug(discussion_slug) do def get_discussion_by_slug(discussion_slug) do
Discussion Discussion
|> Repo.get_by(slug: discussion_slug) |> Repo.get_by(slug: discussion_slug)
@ -494,11 +494,11 @@ defmodule Mobilizon.Discussions do
) )
end end
@spec filter_comments_under_events(Ecto.Query.t()) :: Ecto.Query.t() @spec filter_comments_under_events(Ecto.Queryable.t()) :: Ecto.Query.t()
defp filter_comments_under_events(query) do defp filter_comments_under_events(query) do
where(query, [c], is_nil(c.discussion_id) and not is_nil(c.event_id)) where(query, [c], is_nil(c.discussion_id) and not is_nil(c.event_id))
end end
@spec preload_for_comment(Ecto.Query.t()) :: Ecto.Query.t() @spec preload_for_comment(Ecto.Queryable.t()) :: Ecto.Query.t()
defp preload_for_comment(query), do: preload(query, ^@comment_preloads) defp preload_for_comment(query), do: preload(query, ^@comment_preloads)
end end

View File

@ -35,6 +35,7 @@ defmodule Mobilizon.Events.Event do
alias Mobilizon.Web.Router.Helpers, as: Routes alias Mobilizon.Web.Router.Helpers, as: Routes
@type t :: %__MODULE__{ @type t :: %__MODULE__{
id: String.t(),
url: String.t(), url: String.t(),
local: boolean, local: boolean,
begins_on: DateTime.t(), begins_on: DateTime.t(),
@ -53,7 +54,7 @@ defmodule Mobilizon.Events.Event do
category: String.t(), category: String.t(),
options: EventOptions.t(), options: EventOptions.t(),
organizer_actor: Actor.t(), organizer_actor: Actor.t(),
attributed_to: Actor.t(), attributed_to: Actor.t() | nil,
physical_address: Address.t(), physical_address: Address.t(),
picture: Media.t(), picture: Media.t(),
media: [Media.t()], media: [Media.t()],
@ -130,7 +131,7 @@ defmodule Mobilizon.Events.Event do
end end
@doc false @doc false
@spec changeset(t, map) :: Changeset.t() @spec changeset(t | Ecto.Schema.t(), map) :: Changeset.t()
def changeset(%__MODULE__{} = event, attrs) do def changeset(%__MODULE__{} = event, attrs) do
attrs = Map.update(attrs, :uuid, Ecto.UUID.generate(), & &1) attrs = Map.update(attrs, :uuid, Ecto.UUID.generate(), & &1)
attrs = Map.update(attrs, :url, Routes.page_url(Endpoint, :event, attrs.uuid), & &1) attrs = Map.update(attrs, :url, Routes.page_url(Endpoint, :event, attrs.uuid), & &1)
@ -289,4 +290,12 @@ defmodule Mobilizon.Events.Event do
defp put_creator_if_published(%Changeset{} = changeset, _), defp put_creator_if_published(%Changeset{} = changeset, _),
do: cast_embed(changeset, :participant_stats) do: cast_embed(changeset, :participant_stats)
@doc """
Whether we can show the event. Returns false if the organizer actor or group is suspended
"""
@spec show?(t) :: boolean()
def show?(%__MODULE__{attributed_to: %Actor{suspended: true}}), do: false
def show?(%__MODULE__{organizer_actor: %Actor{suspended: true}}), do: false
def show?(%__MODULE__{}), do: true
end end

View File

@ -36,7 +36,7 @@ defmodule Mobilizon.Events.EventMetadata do
end end
@doc false @doc false
@spec changeset(t, map) :: Ecto.Changeset.t() @spec changeset(t | Ecto.Schema.t(), map) :: Ecto.Changeset.t()
def changeset(%__MODULE__{} = event_metadata, attrs) do def changeset(%__MODULE__{} = event_metadata, attrs) do
event_metadata event_metadata
|> cast(attrs, @attrs) |> cast(attrs, @attrs)

View File

@ -64,7 +64,7 @@ defmodule Mobilizon.Events.EventOptions do
end end
@doc false @doc false
@spec changeset(t, map) :: Ecto.Changeset.t() @spec changeset(t | Ecto.Schema.t(), map) :: Ecto.Changeset.t()
def changeset(%__MODULE__{} = event_options, attrs) do def changeset(%__MODULE__{} = event_options, attrs) do
event_options event_options
|> cast(attrs, @attrs) |> cast(attrs, @attrs)

View File

@ -40,7 +40,7 @@ defmodule Mobilizon.Events.EventParticipantStats do
end end
@doc false @doc false
@spec changeset(t, map) :: Ecto.Changeset.t() @spec changeset(t | Ecto.Schema.t(), map) :: Ecto.Changeset.t()
def changeset(%__MODULE__{} = event_options, attrs) do def changeset(%__MODULE__{} = event_options, attrs) do
event_options event_options
|> cast(attrs, @attrs) |> cast(attrs, @attrs)

View File

@ -263,7 +263,10 @@ defmodule Mobilizon.Events do
@doc """ @doc """
Creates an event. Creates an event.
""" """
@spec create_event(map) :: {:ok, Event.t()} | {:error, Changeset.t()} @spec create_event(map) ::
{:ok, Event.t()}
| {:error, Changeset.t()}
| {:error, :update | :write, Changeset.t(), map()}
def create_event(attrs \\ %{}) do def create_event(attrs \\ %{}) do
with {:ok, %{insert: %Event{} = event}} <- do_create_event(attrs), with {:ok, %{insert: %Event{} = event}} <- do_create_event(attrs),
%Event{} = event <- Repo.preload(event, @event_preloads) do %Event{} = event <- Repo.preload(event, @event_preloads) do
@ -278,7 +281,10 @@ defmodule Mobilizon.Events do
end end
# We start by inserting the event and then insert a first participant if the event is not a draft # We start by inserting the event and then insert a first participant if the event is not a draft
@spec do_create_event(map) :: {:ok, Event.t()} | {:error, Changeset.t()} @spec do_create_event(map) ::
{:ok, Event.t()}
| {:error, Changeset.t()}
| {:error, :update | :write, Changeset.t(), map()}
defp do_create_event(attrs) do defp do_create_event(attrs) do
Multi.new() Multi.new()
|> Multi.insert(:insert, Event.changeset(%Event{}, attrs)) |> Multi.insert(:insert, Event.changeset(%Event{}, attrs))
@ -307,7 +313,10 @@ defmodule Mobilizon.Events do
We start by updating the event and then insert a first participant if the event is not a draft anymore We start by updating the event and then insert a first participant if the event is not a draft anymore
""" """
@spec update_event(Event.t(), map) :: {:ok, Event.t()} | {:error, Changeset.t()} @spec update_event(Event.t(), map) ::
{:ok, Event.t()}
| {:error, Changeset.t()}
| {:error, :update | :write, Changeset.t(), map()}
def update_event(%Event{draft: old_draft} = old_event, attrs) do def update_event(%Event{draft: old_draft} = old_event, attrs) do
with %Event{} = old_event <- Repo.preload(old_event, @event_preloads), with %Event{} = old_event <- Repo.preload(old_event, @event_preloads),
%Changeset{changes: changes} = changeset <- %Changeset{changes: changes} = changeset <-
@ -394,7 +403,7 @@ defmodule Mobilizon.Events do
|> Repo.stream() |> Repo.stream()
end end
@spec list_public_local_events(integer | nil, integer | nil) :: Page.t() @spec list_public_local_events(integer | nil, integer | nil) :: Page.t(Event.t())
def list_public_local_events(page \\ nil, limit \\ nil) do def list_public_local_events(page \\ nil, limit \\ nil) do
Event Event
|> filter_public_visibility() |> filter_public_visibility()
@ -452,7 +461,7 @@ defmodule Mobilizon.Events do
DateTime.t() | nil, DateTime.t() | nil,
integer | nil, integer | nil,
integer | nil integer | nil
) :: Page.t() ) :: Page.t(Event.t())
def list_organized_events_for_group( def list_organized_events_for_group(
%Actor{id: group_id}, %Actor{id: group_id},
visibility \\ :public, visibility \\ :public,
@ -729,7 +738,7 @@ defmodule Mobilizon.Events do
nil nil
""" """
@spec get_participant(integer) :: Participant.t() @spec get_participant(integer) :: Participant.t() | nil
def get_participant(participant_id) do def get_participant(participant_id) do
Participant Participant
|> where([p], p.id == ^participant_id) |> where([p], p.id == ^participant_id)
@ -1040,21 +1049,18 @@ defmodule Mobilizon.Events do
Deletes a participant. Deletes a participant.
""" """
@spec delete_participant(Participant.t()) :: @spec delete_participant(Participant.t()) ::
{:ok, Participant.t()} | {:error, Changeset.t()} {:ok, %{participant: Participant.t()}}
| {:error, :participant | :update_event_participation_stats, Changeset.t(), map()}
def delete_participant(%Participant{role: old_role} = participant) do def delete_participant(%Participant{role: old_role} = participant) do
with {:ok, %{participant: %Participant{} = participant}} <-
Multi.new() Multi.new()
|> Multi.delete(:participant, participant) |> Multi.delete(:participant, participant)
|> Multi.run(:update_event_participation_stats, fn _repo, |> Multi.run(:update_event_participation_stats, fn _repo,
%{ %{
participant: participant: %Participant{} = participant
%Participant{} = participant
} -> } ->
update_participant_stats(participant, old_role, nil) update_participant_stats(participant, old_role, nil)
end) end)
|> Repo.transaction() do |> Repo.transaction()
{:ok, participant}
end
end end
defp update_participant_stats( defp update_participant_stats(
@ -1330,7 +1336,7 @@ defmodule Mobilizon.Events do
) )
end end
@spec user_events_query(Ecto.Query.t(), number()) :: Ecto.Query.t() @spec user_events_query(Ecto.Queryable.t(), number()) :: Ecto.Query.t()
defp user_events_query(query, user_id) do defp user_events_query(query, user_id) do
from( from(
e in query, e in query,
@ -1373,7 +1379,7 @@ defmodule Mobilizon.Events do
) )
end end
@spec events_for_begins_on(Ecto.Query.t(), map()) :: Ecto.Query.t() @spec events_for_begins_on(Ecto.Queryable.t(), map()) :: Ecto.Query.t()
defp events_for_begins_on(query, args) do defp events_for_begins_on(query, args) do
begins_on = Map.get(args, :begins_on, DateTime.utc_now()) begins_on = Map.get(args, :begins_on, DateTime.utc_now())
@ -1381,7 +1387,7 @@ defmodule Mobilizon.Events do
|> where([q], q.begins_on >= ^begins_on) |> where([q], q.begins_on >= ^begins_on)
end end
@spec events_for_ends_on(Ecto.Query.t(), map()) :: Ecto.Query.t() @spec events_for_ends_on(Ecto.Queryable.t(), map()) :: Ecto.Query.t()
defp events_for_ends_on(query, args) do defp events_for_ends_on(query, args) do
ends_on = Map.get(args, :ends_on) ends_on = Map.get(args, :ends_on)
@ -1396,7 +1402,7 @@ defmodule Mobilizon.Events do
) )
end end
@spec events_for_tags(Ecto.Query.t(), map()) :: Ecto.Query.t() @spec events_for_tags(Ecto.Queryable.t(), map()) :: Ecto.Query.t()
defp events_for_tags(query, %{tags: tags}) when is_valid_string(tags) do defp events_for_tags(query, %{tags: tags}) when is_valid_string(tags) do
query query
|> join(:inner, [q], te in "events_tags", on: q.id == te.event_id) |> join(:inner, [q], te in "events_tags", on: q.id == te.event_id)
@ -1406,7 +1412,7 @@ defmodule Mobilizon.Events do
defp events_for_tags(query, _args), do: query defp events_for_tags(query, _args), do: query
@spec events_for_location(Ecto.Query.t(), map()) :: Ecto.Query.t() @spec events_for_location(Ecto.Queryable.t(), map()) :: Ecto.Query.t()
defp events_for_location(query, %{radius: radius}) when is_nil(radius), defp events_for_location(query, %{radius: radius}) when is_nil(radius),
do: query do: query
@ -1472,7 +1478,7 @@ defmodule Mobilizon.Events do
from(t in Tag, where: t.title == ^title, limit: 1) from(t in Tag, where: t.title == ^title, limit: 1)
end end
@spec tag_filter(Ecto.Query.t(), String.t() | nil) :: Ecto.Query.t() @spec tag_filter(Ecto.Queryable.t(), String.t() | nil) :: Ecto.Query.t()
defp tag_filter(query, nil), do: query defp tag_filter(query, nil), do: query
defp tag_filter(query, ""), do: query defp tag_filter(query, ""), do: query
@ -1511,7 +1517,7 @@ defmodule Mobilizon.Events do
) )
end end
@spec tag_relation_union_subquery(Ecto.Query.t(), integer) :: Ecto.Query.t() @spec tag_relation_union_subquery(Ecto.Queryable.t(), integer) :: Ecto.Query.t()
defp tag_relation_union_subquery(subquery, tag_id) do defp tag_relation_union_subquery(subquery, tag_id) do
from( from(
tr in TagRelation, tr in TagRelation,
@ -1521,7 +1527,7 @@ defmodule Mobilizon.Events do
) )
end end
@spec tag_neighbors_query(Ecto.Query.t(), integer, integer) :: Ecto.Query.t() @spec tag_neighbors_query(Ecto.Queryable.t(), integer, integer) :: Ecto.Query.t()
defp tag_neighbors_query(subquery, relation_minimum, limit) do defp tag_neighbors_query(subquery, relation_minimum, limit) do
from( from(
t in Tag, t in Tag,
@ -1673,38 +1679,34 @@ defmodule Mobilizon.Events do
from(tk in FeedToken, where: tk.actor_id == ^actor_id, preload: [:actor, :user]) from(tk in FeedToken, where: tk.actor_id == ^actor_id, preload: [:actor, :user])
end end
@spec filter_public_visibility(Ecto.Query.t()) :: Ecto.Query.t() @spec filter_public_visibility(Ecto.Queryable.t()) :: Ecto.Query.t()
defp filter_public_visibility(query) do defp filter_public_visibility(query) do
from(e in query, where: e.visibility == ^:public) from(e in query, where: e.visibility == ^:public)
end end
@spec filter_unlisted_and_public_visibility(Ecto.Query.t()) :: Ecto.Query.t() @spec filter_unlisted_and_public_visibility(Ecto.Queryable.t()) :: Ecto.Query.t()
defp filter_unlisted_and_public_visibility(query) do defp filter_unlisted_and_public_visibility(query) do
from(q in query, where: q.visibility in ^@public_visibility) from(q in query, where: q.visibility in ^@public_visibility)
end end
@spec filter_not_event_uuid(Ecto.Query.t(), String.t() | nil) :: Ecto.Query.t() @spec filter_not_event_uuid(Ecto.Queryable.t(), String.t() | nil) :: Ecto.Query.t()
defp filter_not_event_uuid(query, nil), do: query defp filter_not_event_uuid(query, nil), do: query
defp filter_not_event_uuid(query, not_event_uuid) do defp filter_not_event_uuid(query, not_event_uuid) do
from(e in query, where: e.uuid != ^not_event_uuid) from(e in query, where: e.uuid != ^not_event_uuid)
end end
@spec filter_draft(Ecto.Query.t(), boolean) :: Ecto.Query.t() @spec filter_draft(Ecto.Queryable.t(), boolean) :: Ecto.Query.t()
defp filter_draft(query, is_draft \\ false) do defp filter_draft(query, is_draft \\ false) do
from(e in query, where: e.draft == ^is_draft) from(e in query, where: e.draft == ^is_draft)
end end
@spec filter_cancelled_events(Ecto.Query.t(), boolean()) :: Ecto.Query.t() @spec filter_cancelled_events(Ecto.Queryable.t()) :: Ecto.Query.t()
defp filter_cancelled_events(query, hide_cancelled \\ true) defp filter_cancelled_events(query) do
defp filter_cancelled_events(query, false), do: query
defp filter_cancelled_events(query, true) do
from(e in query, where: e.status != ^:cancelled) from(e in query, where: e.status != ^:cancelled)
end end
@spec filter_future_events(Ecto.Query.t(), boolean) :: Ecto.Query.t() @spec filter_future_events(Ecto.Queryable.t(), boolean) :: Ecto.Query.t()
defp filter_future_events(query, true) do defp filter_future_events(query, true) do
from(q in query, from(q in query,
where: q.begins_on > ^DateTime.utc_now() where: q.begins_on > ^DateTime.utc_now()
@ -1713,12 +1715,12 @@ defmodule Mobilizon.Events do
defp filter_future_events(query, false), do: query defp filter_future_events(query, false), do: query
@spec filter_local(Ecto.Query.t()) :: Ecto.Query.t() @spec filter_local(Ecto.Queryable.t()) :: Ecto.Query.t()
defp filter_local(query) do defp filter_local(query) do
where(query, [q], q.local == true) where(query, [q], q.local == true)
end end
@spec filter_local_or_from_followed_instances_events(Ecto.Query.t()) :: @spec filter_local_or_from_followed_instances_events(Ecto.Queryable.t()) ::
Ecto.Query.t() Ecto.Query.t()
defp filter_local_or_from_followed_instances_events(query) do defp filter_local_or_from_followed_instances_events(query) do
follower_actor_id = Mobilizon.Config.relay_actor_id() follower_actor_id = Mobilizon.Config.relay_actor_id()
@ -1732,22 +1734,22 @@ defmodule Mobilizon.Events do
) )
end end
@spec filter_approved_role(Ecto.Query.t()) :: Ecto.Query.t() @spec filter_approved_role(Ecto.Queryable.t()) :: Ecto.Query.t()
defp filter_approved_role(query) do defp filter_approved_role(query) do
filter_role(query, [:not_approved, :rejected]) filter_role(query, [:not_approved, :rejected])
end end
@spec filter_participant_role(Ecto.Query.t()) :: Ecto.Query.t() @spec filter_participant_role(Ecto.Queryable.t()) :: Ecto.Query.t()
defp filter_participant_role(query) do defp filter_participant_role(query) do
filter_role(query, :participant) filter_role(query, :participant)
end end
@spec filter_rejected_role(Ecto.Query.t()) :: Ecto.Query.t() @spec filter_rejected_role(Ecto.Queryable.t()) :: Ecto.Query.t()
defp filter_rejected_role(query) do defp filter_rejected_role(query) do
filter_role(query, :rejected) filter_role(query, :rejected)
end end
@spec filter_role(Ecto.Query.t(), list(atom())) :: Ecto.Query.t() @spec filter_role(Ecto.Queryable.t(), list(atom()) | atom()) :: Ecto.Query.t()
def filter_role(query, []), do: query def filter_role(query, []), do: query
def filter_role(query, roles) when is_list(roles) do def filter_role(query, roles) when is_list(roles) do
@ -1829,6 +1831,6 @@ defmodule Mobilizon.Events do
defp participation_order_begins_on_desc(query), defp participation_order_begins_on_desc(query),
do: order_by(query, [_p, e, _a], desc: e.begins_on) do: order_by(query, [_p, e, _a], desc: e.begins_on)
@spec preload_for_event(Ecto.Query.t()) :: Ecto.Query.t() @spec preload_for_event(Ecto.Queryable.t()) :: Ecto.Query.t()
defp preload_for_event(query), do: preload(query, ^@event_preloads) defp preload_for_event(query), do: preload(query, ^@event_preloads)
end end

View File

@ -12,7 +12,7 @@ defmodule Mobilizon.Events.FeedToken do
@type t :: %__MODULE__{ @type t :: %__MODULE__{
token: Ecto.UUID.t(), token: Ecto.UUID.t(),
actor: Actor.t(), actor: Actor.t() | nil,
user: User.t() user: User.t()
} }
@ -31,7 +31,7 @@ defmodule Mobilizon.Events.FeedToken do
end end
@doc false @doc false
@spec changeset(t, map) :: Ecto.Changeset.t() @spec changeset(t | Ecto.Schema.t(), map) :: Ecto.Changeset.t()
def changeset(%__MODULE__{} = feed_token, attrs) do def changeset(%__MODULE__{} = feed_token, attrs) do
feed_token feed_token
|> cast(attrs, @attrs) |> cast(attrs, @attrs)

View File

@ -57,7 +57,7 @@ defmodule Mobilizon.Events.Participant do
end end
@doc false @doc false
@spec changeset(t, map) :: Ecto.Changeset.t() @spec changeset(t | Ecto.Schema.t(), map) :: Ecto.Changeset.t()
def changeset(%__MODULE__{} = participant, attrs) do def changeset(%__MODULE__{} = participant, attrs) do
participant participant
|> cast(attrs, @attrs) |> cast(attrs, @attrs)

View File

@ -27,7 +27,7 @@ defmodule Mobilizon.Events.Participant.Metadata do
end end
@doc false @doc false
@spec changeset(t, map) :: Ecto.Changeset.t() @spec changeset(t | Ecto.Schema.t(), map) :: Ecto.Changeset.t()
def changeset(schema, params) do def changeset(schema, params) do
schema schema
|> cast(params, @attrs) |> cast(params, @attrs)

View File

@ -56,7 +56,7 @@ defmodule Mobilizon.Events.Session do
end end
@doc false @doc false
@spec changeset(t, map) :: Ecto.Changeset.t() @spec changeset(t | Ecto.Schema.t(), map) :: Ecto.Changeset.t()
def changeset(%__MODULE__{} = session, attrs) do def changeset(%__MODULE__{} = session, attrs) do
session session
|> cast(attrs, @attrs) |> cast(attrs, @attrs)

View File

@ -29,7 +29,7 @@ defmodule Mobilizon.Events.Tag do
end end
@doc false @doc false
@spec changeset(t, map) :: Ecto.Changeset.t() @spec changeset(t | Ecto.Schema.t(), map) :: Ecto.Changeset.t()
def changeset(%__MODULE__{} = tag, attrs) do def changeset(%__MODULE__{} = tag, attrs) do
tag tag
|> cast(attrs, @attrs) |> cast(attrs, @attrs)

View File

@ -28,7 +28,7 @@ defmodule Mobilizon.Events.TagRelation do
end end
@doc false @doc false
@spec changeset(t, map) :: Ecto.Changeset.t() @spec changeset(t | Ecto.Schema.t(), map) :: Ecto.Changeset.t()
def changeset(%__MODULE__{} = tag, attrs) do def changeset(%__MODULE__{} = tag, attrs) do
# Return if tag_id or link_id are not set because it will fail later otherwise # Return if tag_id or link_id are not set because it will fail later otherwise
with %Ecto.Changeset{errors: [], changes: changes} = changeset <- with %Ecto.Changeset{errors: [], changes: changes} = changeset <-

View File

@ -33,7 +33,7 @@ defmodule Mobilizon.Events.Track do
end end
@doc false @doc false
@spec changeset(t, map) :: Ecto.Changeset.t() @spec changeset(t | Ecto.Schema.t(), map) :: Ecto.Changeset.t()
def changeset(%__MODULE__{} = track, attrs) do def changeset(%__MODULE__{} = track, attrs) do
track track
|> cast(attrs, @attrs) |> cast(attrs, @attrs)

View File

@ -29,7 +29,7 @@ defmodule Mobilizon.Medias.File do
end end
@doc false @doc false
@spec changeset(t, map) :: Ecto.Changeset.t() @spec changeset(t | Ecto.Schema.t(), map) :: Ecto.Changeset.t()
def changeset(%__MODULE__{} = file, attrs) do def changeset(%__MODULE__{} = file, attrs) do
file file
|> cast(attrs, @attrs) |> cast(attrs, @attrs)

View File

@ -42,7 +42,7 @@ defmodule Mobilizon.Medias.Media do
end end
@doc false @doc false
@spec changeset(t, map) :: Ecto.Changeset.t() @spec changeset(t | Ecto.Schema.t(), map) :: Ecto.Changeset.t()
def changeset(%__MODULE__{} = media, attrs) do def changeset(%__MODULE__{} = media, attrs) do
media media
|> cast(attrs, [:actor_id]) |> cast(attrs, [:actor_id])

View File

@ -130,7 +130,7 @@ defmodule Mobilizon.Medias do
|> Multi.run(:remove, fn _repo, %{media: %Media{file: %File{url: url}} = media} -> |> Multi.run(:remove, fn _repo, %{media: %Media{file: %File{url: url}} = media} ->
case Upload.remove(url) do case Upload.remove(url) do
{:error, err} -> {:error, err} ->
if err =~ "doesn't exist" and Keyword.get(opts, :ignore_file_not_found, false) do if err == :enofile and Keyword.get(opts, :ignore_file_not_found, false) do
Logger.info("Deleting media and ignoring absent file.") Logger.info("Deleting media and ignoring absent file.")
{:ok, media} {:ok, media}
else else

View File

@ -31,6 +31,7 @@ defmodule Mobilizon.Mention do
end end
@doc false @doc false
@spec changeset(t | Ecto.Schema.t(), map) :: Ecto.Changeset.t()
def changeset(event, attrs) do def changeset(event, attrs) do
event event
|> cast(attrs, @attrs) |> cast(attrs, @attrs)

View File

@ -82,6 +82,7 @@ defmodule Mobilizon.Posts.Post do
@attrs @required_attrs ++ @optional_attrs @attrs @required_attrs ++ @optional_attrs
@doc false @doc false
@spec changeset(t | Ecto.Schema.t(), map) :: Ecto.Changeset.t()
def changeset(%__MODULE__{} = post, attrs) do def changeset(%__MODULE__{} = post, attrs) do
post post
|> cast(attrs, @attrs) |> cast(attrs, @attrs)
@ -153,17 +154,20 @@ defmodule Mobilizon.Posts.Post do
# In case the provided picture is an existing one # In case the provided picture is an existing one
@spec put_picture(Changeset.t(), map) :: Changeset.t() @spec put_picture(Changeset.t(), map) :: Changeset.t()
defp put_picture(%Changeset{} = changeset, %{picture: %{picture_id: id} = _picture}) do defp put_picture(%Changeset{} = changeset, %{picture: %{picture_id: id} = _picture}) do
case Medias.get_media!(id) do %Media{} = picture = Medias.get_media!(id)
%Media{} = picture ->
put_assoc(changeset, :picture, picture) put_assoc(changeset, :picture, picture)
_ ->
changeset
end
end end
# In case it's a new picture # In case it's a new picture
defp put_picture(%Changeset{} = changeset, _attrs) do defp put_picture(%Changeset{} = changeset, _attrs) do
cast_assoc(changeset, :picture) cast_assoc(changeset, :picture)
end end
@doc """
Whether we can show the post. Returns false if the organizer actor or group is suspended
"""
@spec show?(t) :: boolean()
def show?(%__MODULE__{attributed_to: %Actor{suspended: true}}), do: false
def show?(%__MODULE__{author: %Actor{suspended: true}}), do: false
def show?(%__MODULE__{}), do: true
end end

View File

@ -21,6 +21,7 @@ defmodule Mobilizon.Posts do
:private :private
]) ])
@spec list_public_local_posts(integer | nil, integer | nil) :: Page.t(Post.t())
def list_public_local_posts(page \\ nil, limit \\ nil) do def list_public_local_posts(page \\ nil, limit \\ nil) do
Post Post
|> filter_public() |> filter_public()
@ -144,12 +145,12 @@ defmodule Mobilizon.Posts do
) )
end end
@spec filter_public(Ecto.Query.t()) :: Ecto.Query.t() @spec filter_public(Ecto.Queryable.t()) :: Ecto.Query.t()
defp filter_public(query) do defp filter_public(query) do
where(query, [p], p.visibility == ^:public and not p.draft) where(query, [p], p.visibility == ^:public and not p.draft)
end end
@spec filter_local(Ecto.Query.t()) :: Ecto.Query.t() @spec filter_local(Ecto.Queryable.t()) :: Ecto.Query.t()
defp filter_local(query) do defp filter_local(query) do
where(query, [q], q.local == true) where(query, [q], q.local == true)
end end
@ -161,7 +162,7 @@ defmodule Mobilizon.Posts do
|> preload_post_associations() |> preload_post_associations()
end end
@spec preload_post_associations(Ecto.Query.t(), list()) :: Ecto.Query.t() @spec preload_post_associations(Ecto.Queryable.t(), list()) :: Ecto.Query.t()
defp preload_post_associations(query, associations \\ @post_preloads) do defp preload_post_associations(query, associations \\ @post_preloads) do
preload(query, ^associations) preload(query, ^associations)
end end

View File

@ -32,7 +32,7 @@ defmodule Mobilizon.Reports.Note do
end end
@doc false @doc false
@spec changeset(t, map) :: Ecto.Changeset.t() @spec changeset(t | Ecto.Schema.t(), map) :: Ecto.Changeset.t()
def changeset(%__MODULE__{} = note, attrs) do def changeset(%__MODULE__{} = note, attrs) do
note note
|> cast(attrs, @attrs) |> cast(attrs, @attrs)

View File

@ -56,7 +56,7 @@ defmodule Mobilizon.Reports.Report do
end end
@doc false @doc false
@spec changeset(t, map) :: Ecto.Changeset.t() @spec changeset(t | Ecto.Schema.t(), map) :: Ecto.Changeset.t()
def changeset(%__MODULE__{} = report, attrs) do def changeset(%__MODULE__{} = report, attrs) do
report report
|> cast(attrs, @attrs) |> cast(attrs, @attrs)

View File

@ -79,6 +79,7 @@ defmodule Mobilizon.Resources.Resource do
] ]
@doc false @doc false
@spec changeset(t | Ecto.Schema.t(), map) :: Ecto.Changeset.t()
def changeset(resource, attrs) do def changeset(resource, attrs) do
resource resource
|> cast(attrs, @attrs) |> cast(attrs, @attrs)

View File

@ -29,6 +29,7 @@ defmodule Mobilizon.Share do
end end
@doc false @doc false
@spec changeset(t | Ecto.Schema.t(), map()) :: Ecto.Changeset.t()
def changeset(share, attrs) do def changeset(share, attrs) do
share share
|> cast(attrs, @attrs) |> cast(attrs, @attrs)

View File

@ -12,9 +12,9 @@ defmodule Mobilizon.Storage.Page do
:elements :elements
] ]
@type t :: %__MODULE__{ @type t(structure) :: %__MODULE__{
total: integer, total: integer,
elements: struct elements: list(structure)
} }
@doc """ @doc """
@ -23,7 +23,7 @@ defmodule Mobilizon.Storage.Page do
`field` is use to define the field that will be used for the count aggregate, which should be the same as the field used for order_by `field` is use to define the field that will be used for the count aggregate, which should be the same as the field used for order_by
See https://stackoverflow.com/q/12693089/10204399 See https://stackoverflow.com/q/12693089/10204399
""" """
@spec build_page(Ecto.Query.t(), integer | nil, integer | nil, atom()) :: t @spec build_page(Ecto.Queryable.t(), integer | nil, integer | nil, atom()) :: t(any)
def build_page(query, page, limit, field \\ :id) do def build_page(query, page, limit, field \\ :id) do
[total, elements] = [total, elements] =
[ [
@ -39,7 +39,7 @@ defmodule Mobilizon.Storage.Page do
@doc """ @doc """
Add limit and offset to the query. Add limit and offset to the query.
""" """
@spec paginate(Ecto.Query.t() | struct, integer | nil, integer | nil) :: Ecto.Query.t() @spec paginate(Ecto.Queryable.t() | struct, integer | nil, integer | nil) :: Ecto.Query.t()
def paginate(query, page \\ 1, size \\ 10) def paginate(query, page \\ 1, size \\ 10)
def paginate(query, page, _size) when is_nil(page), do: paginate(query) def paginate(query, page, _size) when is_nil(page), do: paginate(query)

View File

@ -40,6 +40,7 @@ defmodule Mobilizon.Todos.Todo do
@attrs @required_attrs ++ @optional_attrs @attrs @required_attrs ++ @optional_attrs
@doc false @doc false
@spec changeset(t | Ecto.Schema.t(), map) :: Ecto.Changeset.t()
def changeset(todo, attrs) do def changeset(todo, attrs) do
todo todo
|> cast(attrs, @attrs) |> cast(attrs, @attrs)

View File

@ -34,6 +34,7 @@ defmodule Mobilizon.Todos.TodoList do
@attrs @required_attrs ++ @optional_attrs @attrs @required_attrs ++ @optional_attrs
@doc false @doc false
@spec changeset(t | Ecto.Schema.t(), map) :: Ecto.Changeset.t()
def changeset(todo_list, attrs) do def changeset(todo_list, attrs) do
todo_list todo_list
|> cast(attrs, @attrs) |> cast(attrs, @attrs)

View File

@ -26,20 +26,21 @@ defmodule Mobilizon.Tombstone do
end end
@doc false @doc false
@spec changeset(t | Ecto.Schema.t(), map()) :: Ecto.Changeset.t()
def changeset(%__MODULE__{} = tombstone, attrs) do def changeset(%__MODULE__{} = tombstone, attrs) do
tombstone tombstone
|> cast(attrs, @attrs) |> cast(attrs, @attrs)
|> validate_required(@required_attrs) |> validate_required(@required_attrs)
end end
@spec create_tombstone(map) :: {:ok, Ecto.Schema.t()} | {:error, Ecto.Changeset.t()} @spec create_tombstone(map) :: {:ok, t()} | {:error, Ecto.Changeset.t()}
def create_tombstone(attrs) do def create_tombstone(attrs) do
%__MODULE__{} %__MODULE__{}
|> changeset(attrs) |> changeset(attrs)
|> Repo.insert(on_conflict: :replace_all, conflict_target: :uri) |> Repo.insert(on_conflict: :replace_all, conflict_target: :uri)
end end
@spec find_tombstone(String.t()) :: Ecto.Schema.t() | nil @spec find_tombstone(String.t()) :: t() | nil
def find_tombstone(uri) do def find_tombstone(uri) do
__MODULE__ __MODULE__
|> Ecto.Query.where([t], t.uri == ^uri) |> Ecto.Query.where([t], t.uri == ^uri)
@ -54,6 +55,7 @@ defmodule Mobilizon.Tombstone do
|> Repo.delete_all() |> Repo.delete_all()
end end
@spec delete_uri_tombstone(String.t()) :: {integer(), nil}
def delete_uri_tombstone(uri) do def delete_uri_tombstone(uri) do
__MODULE__ __MODULE__
|> Ecto.Query.where(uri: ^uri) |> Ecto.Query.where(uri: ^uri)

View File

@ -25,6 +25,7 @@ defmodule Mobilizon.Users.ActivitySetting do
end end
@doc false @doc false
@spec changeset(t | Ecto.Schema.t(), map) :: Ecto.Changeset.t()
def changeset(activity_setting, attrs) do def changeset(activity_setting, attrs) do
activity_setting activity_setting
|> cast(attrs, @attrs) |> cast(attrs, @attrs)

View File

@ -25,6 +25,7 @@ defmodule Mobilizon.Users.PushSubscription do
end end
@doc false @doc false
@spec changeset(t | Ecto.Schema.t(), map) :: Ecto.Changeset.t()
def changeset(push_subscription, attrs) do def changeset(push_subscription, attrs) do
push_subscription push_subscription
|> cast(attrs, [:user_id, :endpoint, :auth, :p256dh]) |> cast(attrs, [:user_id, :endpoint, :auth, :p256dh])

View File

@ -19,6 +19,12 @@ defmodule Mobilizon.Users.Setting do
user: User.t() user: User.t()
} }
@type location :: %{
name: String.t(),
range: integer,
geohash: String.t()
}
@required_attrs [:user_id] @required_attrs [:user_id]
@optional_attrs [ @optional_attrs [
@ -66,6 +72,7 @@ defmodule Mobilizon.Users.Setting do
end end
@doc false @doc false
@spec changeset(t | Ecto.Schema.t(), map) :: Ecto.Changeset.t()
def changeset(setting, attrs) do def changeset(setting, attrs) do
setting setting
|> cast(attrs, @attrs) |> cast(attrs, @attrs)
@ -73,6 +80,7 @@ defmodule Mobilizon.Users.Setting do
|> validate_required(@required_attrs) |> validate_required(@required_attrs)
end end
@spec location_changeset(location, map) :: Ecto.Changeset.t()
def location_changeset(schema, params) do def location_changeset(schema, params) do
schema schema
|> cast(params, @location_attrs) |> cast(params, @location_attrs)

View File

@ -19,7 +19,7 @@ defmodule Mobilizon.Users.User do
password_hash: String.t(), password_hash: String.t(),
password: String.t(), password: String.t(),
role: UserRole.t(), role: UserRole.t(),
confirmed_at: DateTime.t(), confirmed_at: DateTime.t() | nil,
confirmation_sent_at: DateTime.t(), confirmation_sent_at: DateTime.t(),
confirmation_token: String.t(), confirmation_token: String.t(),
reset_password_sent_at: DateTime.t(), reset_password_sent_at: DateTime.t(),
@ -32,7 +32,10 @@ defmodule Mobilizon.Users.User do
last_sign_in_at: DateTime.t(), last_sign_in_at: DateTime.t(),
last_sign_in_ip: String.t(), last_sign_in_ip: String.t(),
current_sign_in_ip: String.t(), current_sign_in_ip: String.t(),
current_sign_in_at: DateTime.t() current_sign_in_at: DateTime.t(),
activity_settings: [ActivitySetting.t()],
settings: Setting.t(),
unconfirmed_email: String.t() | nil
} }
@required_attrs [:email] @required_attrs [:email]
@ -96,7 +99,7 @@ defmodule Mobilizon.Users.User do
end end
@doc false @doc false
@spec changeset(t, map) :: Ecto.Changeset.t() @spec changeset(t | Ecto.Schema.t(), map) :: Ecto.Changeset.t()
def changeset(%__MODULE__{} = user, attrs) do def changeset(%__MODULE__{} = user, attrs) do
changeset = changeset =
user user
@ -129,7 +132,6 @@ defmodule Mobilizon.Users.User do
def registration_changeset(%__MODULE__{} = user, attrs) do def registration_changeset(%__MODULE__{} = user, attrs) do
user user
|> changeset(attrs) |> changeset(attrs)
|> cast_assoc(:default_actor)
|> validate_required(@registration_required_attrs) |> validate_required(@registration_required_attrs)
|> hash_password() |> hash_password()
|> save_confirmation_token() |> save_confirmation_token()
@ -148,7 +150,6 @@ defmodule Mobilizon.Users.User do
def auth_provider_changeset(%__MODULE__{} = user, attrs) do def auth_provider_changeset(%__MODULE__{} = user, attrs) do
user user
|> changeset(attrs) |> changeset(attrs)
|> cast_assoc(:default_actor)
|> put_change(:confirmed_at, DateTime.utc_now() |> DateTime.truncate(:second)) |> put_change(:confirmed_at, DateTime.utc_now() |> DateTime.truncate(:second))
|> validate_required(@auth_provider_required_attrs) |> validate_required(@auth_provider_required_attrs)
end end

View File

@ -338,10 +338,10 @@ defmodule Mobilizon.Users do
""" """
def get_setting!(user_id), do: Repo.get!(Setting, user_id) def get_setting!(user_id), do: Repo.get!(Setting, user_id)
@spec get_setting(User.t()) :: Setting.t() @spec get_setting(User.t()) :: Setting.t() | nil
def get_setting(%User{id: user_id}), do: get_setting(user_id) def get_setting(%User{id: user_id}), do: get_setting(user_id)
@spec get_setting(String.t() | integer()) :: Setting.t() @spec get_setting(String.t() | integer()) :: Setting.t() | nil
def get_setting(user_id), do: Repo.get(Setting, user_id) def get_setting(user_id), do: Repo.get(Setting, user_id)
@doc """ @doc """
@ -356,6 +356,7 @@ defmodule Mobilizon.Users do
{:error, %Ecto.Changeset{}} {:error, %Ecto.Changeset{}}
""" """
@spec create_setting(map()) :: {:ok, Setting.t()} | {:error, Ecto.Changeset.t()}
def create_setting(attrs \\ %{}) do def create_setting(attrs \\ %{}) do
%Setting{} %Setting{}
|> Setting.changeset(attrs) |> Setting.changeset(attrs)
@ -445,6 +446,8 @@ defmodule Mobilizon.Users do
{:error, %Ecto.Changeset{}} {:error, %Ecto.Changeset{}}
""" """
@spec create_push_subscription(map()) ::
{:ok, PushSubscription.t()} | {:error, Ecto.Changeset.t()}
def create_push_subscription(attrs \\ %{}) do def create_push_subscription(attrs \\ %{}) do
%PushSubscription{} %PushSubscription{}
|> PushSubscription.changeset(attrs) |> PushSubscription.changeset(attrs)

View File

@ -51,11 +51,11 @@ defmodule Mobilizon.Service.Activity.Comment do
"object_type" => :comment "object_type" => :comment
} }
@spec handle_notification(Keyword.t(), notification_type, Comment.t(), Event.t(), Keyword.t()) ::
Keyword.t()
defp handle_notification(global_res, function, comment, event, options) do defp handle_notification(global_res, function, comment, event, options) do
case notify(function, comment, event, options) do {:ok, res} = notify(function, comment, event, options)
{:ok, res} -> Keyword.put(global_res, function, res) Keyword.put(global_res, function, res)
_ -> Keyword.put(global_res, function, :error)
end
end end
@spec legacy_notifier_enqueue(map()) :: :ok @spec legacy_notifier_enqueue(map()) :: :ok
@ -66,11 +66,11 @@ defmodule Mobilizon.Service.Activity.Comment do
) )
end end
@type notification_type :: atom() @type notification_type :: :mentionned | :announcement | :organizer
# An actor is mentionned # An actor is mentionned
@spec notify(notification_type(), Comment.t(), Event.t(), Keyword.t()) :: @spec notify(notification_type(), Comment.t(), Event.t(), Keyword.t()) ::
{:ok, Oban.Job.t()} | {:ok, :skipped} {:ok, :enqueued} | {:ok, :skipped}
defp notify( defp notify(
:mentionned, :mentionned,
%Comment{actor_id: actor_id, id: comment_id, mentions: mentions}, %Comment{actor_id: actor_id, id: comment_id, mentions: mentions},

View File

@ -10,19 +10,22 @@ defmodule Mobilizon.Service.Activity.Group do
@behaviour Activity @behaviour Activity
@impl Activity @impl Activity
@spec insert_activity(Actor.t(), Keyword.t()) ::
{:ok, Job.t()} | {:ok, nil} | {:error, Ecto.Changeset.t()}
def insert_activity(group, options \\ []) def insert_activity(group, options \\ [])
def insert_activity( def insert_activity(
%Actor{type: :Group, id: group_id}, %Actor{type: :Group, id: group_id},
options options
) do ) do
with %Actor{type: :Group} = group <- Actors.get_actor(group_id), subject = Keyword.get(options, :subject)
subject when not is_nil(subject) <- Keyword.get(options, :subject), actor_id = Keyword.get(options, :actor_id)
actor_id <- Keyword.get(options, :actor_id), default_updater_actor = Actors.get_actor(actor_id)
default_updater_actor <- Actors.get_actor(actor_id), %Actor{id: actor_id} = Keyword.get(options, :updater_actor, default_updater_actor)
%Actor{id: actor_id} <- old_group = Keyword.get(options, :old_group)
Keyword.get(options, :updater_actor, default_updater_actor),
old_group <- Keyword.get(options, :old_group) do case Actors.get_actor(group_id) do
%Actor{type: :Group} = group ->
ActivityBuilder.enqueue(:build_activity, %{ ActivityBuilder.enqueue(:build_activity, %{
"type" => "group", "type" => "group",
"subject" => subject, "subject" => subject,
@ -33,8 +36,9 @@ defmodule Mobilizon.Service.Activity.Group do
"object_id" => to_string(group.id), "object_id" => to_string(group.id),
"inserted_at" => DateTime.utc_now() "inserted_at" => DateTime.utc_now()
}) })
else
_ -> {:ok, nil} nil ->
{:ok, nil}
end end
end end

View File

@ -12,9 +12,9 @@ defmodule Mobilizon.Service.Activity.Utils do
|> add_activity_object() |> add_activity_object()
end end
@spec add_activity_object(Activity.t()) :: map() @spec add_activity_object(Activity.t()) :: Activity.t()
def add_activity_object(%Activity{} = activity) do def add_activity_object(%Activity{} = activity) do
Map.put(activity, :object, ActivityService.object(activity)) %Activity{activity | object: ActivityService.object(activity)}
end end
@spec transform_params(map()) :: list() @spec transform_params(map()) :: list()

View File

@ -7,6 +7,7 @@ defmodule Mobilizon.Service.Address do
@type address :: %{name: String.t(), alternative_name: String.t()} @type address :: %{name: String.t(), alternative_name: String.t()}
@spec render_address(AddressModel.t()) :: String.t() | no_return
def render_address(%AddressModel{} = address) do def render_address(%AddressModel{} = address) do
%{name: name, alternative_name: alternative_name} = render_names(address) %{name: name, alternative_name: alternative_name} = render_names(address)

View File

@ -31,7 +31,7 @@ defmodule Mobilizon.Service.CleanOldActivity do
end end
end end
@spec find_activities(Keyword.t()) :: {Ecto.Query.t(), list()} @spec find_activities(Keyword.t()) :: {Ecto.Query.t(), integer()}
defp find_activities(opts) do defp find_activities(opts) do
grace_period = grace_period =
Keyword.get(opts, :grace_period, Config.get([:instance, :activity_expire_days], 365)) Keyword.get(opts, :grace_period, Config.get([:instance, :activity_expire_days], 365))

View File

@ -3,9 +3,10 @@ defmodule Mobilizon.Service.CleanUnconfirmedUsers do
Service to clean unconfirmed users Service to clean unconfirmed users
""" """
alias Mobilizon.{Actors, Users}
alias Mobilizon.Federation.ActivityPub.Relay alias Mobilizon.Federation.ActivityPub.Relay
alias Mobilizon.Service.ActorSuspension
alias Mobilizon.Storage.Repo alias Mobilizon.Storage.Repo
alias Mobilizon.Users
alias Mobilizon.Users.User alias Mobilizon.Users.User
import Ecto.Query import Ecto.Query
@ -27,21 +28,21 @@ defmodule Mobilizon.Service.CleanUnconfirmedUsers do
end end
end end
@spec delete_user(User.t()) :: {:ok, User.t()} @spec delete_user(User.t()) :: User.t() | {:error, Ecto.Changeset.t()} | no_return
defp delete_user(%User{} = user) do defp delete_user(%User{} = user) do
with actors <- Users.get_actors_for_user(user), actors = Users.get_actors_for_user(user)
:ok <- %{id: actor_performing_id} = Relay.get_actor()
Enum.each(actors, fn actor ->
actor_performing = Relay.get_actor()
Actors.perform(:delete_actor, actor, Enum.each(actors, fn actor ->
author_id: actor_performing.id, ActorSuspension.suspend_actor(actor,
author_id: actor_performing_id,
reserve_username: false reserve_username: false
) )
end), end)
{:ok, %User{} = user} <- Users.delete_user(user, reserve_email: false),
%User{} = user <- %User{user | actors: actors} do case Users.delete_user(user, reserve_email: false) do
user {:ok, %User{} = user} ->
%User{user | actors: actors}
end end
end end

View File

@ -4,10 +4,14 @@ defmodule Mobilizon.Service.DateTime do
""" """
alias Cldr.DateTime.Relative alias Cldr.DateTime.Relative
@typep to_string_format :: :short | :medium | :long | :full
@spec datetime_to_string(DateTime.t(), String.t(), to_string_format()) :: String.t()
def datetime_to_string(%DateTime{} = datetime, locale \\ "en", format \\ :medium) do def datetime_to_string(%DateTime{} = datetime, locale \\ "en", format \\ :medium) do
Mobilizon.Cldr.DateTime.to_string!(datetime, format: format, locale: locale_or_default(locale)) Mobilizon.Cldr.DateTime.to_string!(datetime, format: format, locale: locale_or_default(locale))
end end
@spec datetime_to_time_string(DateTime.t(), String.t(), to_string_format()) :: String.t()
def datetime_to_time_string(%DateTime{} = datetime, locale \\ "en", format \\ :short) do def datetime_to_time_string(%DateTime{} = datetime, locale \\ "en", format \\ :short) do
Mobilizon.Cldr.Time.to_string!(datetime, format: format, locale: locale_or_default(locale)) Mobilizon.Cldr.Time.to_string!(datetime, format: format, locale: locale_or_default(locale))
end end
@ -39,7 +43,8 @@ defmodule Mobilizon.Service.DateTime do
end end
end end
def is_first_day_of_week(%Date{} = date, locale \\ "en") do @spec is_first_day_of_week(Date.t(), String.t()) :: boolean()
defp is_first_day_of_week(%Date{} = date, locale) do
Date.day_of_week(date) == Cldr.Calendar.first_day_for_locale(locale) Date.day_of_week(date) == Cldr.Calendar.first_day_for_locale(locale)
end end
@ -119,17 +124,18 @@ defmodule Mobilizon.Service.DateTime do
compare_to compare_to
|> DateTime.to_date() |> DateTime.to_date()
|> calculate_first_day_of_week(locale) |> calculate_first_day_of_week(locale)
|> Timex.add(Timex.Duration.from_weeks(1)) |> Date.add(7)
|> build_notification_datetime(options) |> build_notification_datetime(options)
if Date.compare(datetime, next_first_day_of_week) == :gt do if next_first_day_of_week != nil && DateTime.compare(datetime, next_first_day_of_week) == :gt do
next_first_day_of_week next_first_day_of_week
else else
nil nil
end end
end end
def appropriate_first_day_of_week(%DateTime{} = datetime, options) do @spec appropriate_first_day_of_week(DateTime.t(), keyword) :: DateTime.t() | nil
defp appropriate_first_day_of_week(%DateTime{} = datetime, options) do
locale = Keyword.get(options, :locale, "en") locale = Keyword.get(options, :locale, "en")
timezone = Keyword.get(options, :timezone, "Etc/UTC") timezone = Keyword.get(options, :timezone, "Etc/UTC")
@ -141,12 +147,17 @@ defmodule Mobilizon.Service.DateTime do
if DateTime.compare(local_datetime, first_datetime) == :gt do if DateTime.compare(local_datetime, first_datetime) == :gt do
first_datetime first_datetime
else else
next_first_day_of_week(local_datetime, options) local_datetime
|> next_first_day_of_week(options)
|> build_notification_datetime(options)
end end
end end
@spec build_notification_datetime(Date.t(), Keyword.t()) :: DateTime.t() @spec build_notification_datetime(Date.t(), Keyword.t()) :: DateTime.t()
def build_notification_datetime( @spec build_notification_datetime(nil, Keyword.t()) :: nil
defp build_notification_datetime(nil, _options), do: nil
defp build_notification_datetime(
%Date{} = date, %Date{} = date,
options options
) do ) do
@ -158,8 +169,8 @@ defmodule Mobilizon.Service.DateTime do
@start_time ~T[08:00:00] @start_time ~T[08:00:00]
@end_time ~T[09:00:00] @end_time ~T[09:00:00]
@spec is_between_hours(Keyword.t()) :: boolean() @spec is_between_hours?(Keyword.t()) :: boolean()
def is_between_hours(options \\ []) when is_list(options) do def is_between_hours?(options \\ []) when is_list(options) do
compare_to_day = Keyword.get(options, :compare_to_day, Date.utc_today()) compare_to_day = Keyword.get(options, :compare_to_day, Date.utc_today())
compare_to = Keyword.get(options, :compare_to_datetime, DateTime.utc_now()) compare_to = Keyword.get(options, :compare_to_datetime, DateTime.utc_now())
start_time = Keyword.get(options, :start_time, @start_time) start_time = Keyword.get(options, :start_time, @start_time)
@ -176,17 +187,16 @@ defmodule Mobilizon.Service.DateTime do
) == :lt ) == :lt
end end
@spec is_between_hours_on_first_day(Keyword.t()) :: boolean() @spec is_between_hours_on_first_day?(Keyword.t()) :: boolean()
def is_between_hours_on_first_day(options) when is_list(options) do def is_between_hours_on_first_day?(options) when is_list(options) do
compare_to_day = Keyword.get(options, :compare_to_day, Date.utc_today()) compare_to_day = Keyword.get(options, :compare_to_day, Date.utc_today())
locale = Keyword.get(options, :locale, "en") locale = Keyword.get(options, :locale, "en")
Mobilizon.Service.DateTime.is_first_day_of_week(compare_to_day, locale) && is_first_day_of_week(compare_to_day, locale) && is_between_hours?(options)
is_between_hours(options)
end end
@spec is_delay_ok_since_last_notification_sent(DateTime.t()) :: boolean() @spec is_delay_ok_since_last_notification_sent?(DateTime.t()) :: boolean()
def is_delay_ok_since_last_notification_sent(%DateTime{} = last_notification_sent) do def is_delay_ok_since_last_notification_sent?(%DateTime{} = last_notification_sent) do
DateTime.compare(DateTime.add(last_notification_sent, 3_600), DateTime.utc_now()) == DateTime.compare(DateTime.add(last_notification_sent, 3_600), DateTime.utc_now()) ==
:lt :lt
end end

View File

@ -29,6 +29,7 @@ defmodule Mobilizon.Service.ErrorReporting.Sentry do
end end
@impl ErrorReporting @impl ErrorReporting
@spec attach :: :ok | {:error, :already_exists}
def attach do def attach do
:telemetry.attach( :telemetry.attach(
"oban-errors", "oban-errors",

View File

@ -6,30 +6,75 @@ defmodule Mobilizon.Service.Export.Common do
alias Mobilizon.{Actors, Events, Posts, Users} alias Mobilizon.{Actors, Events, Posts, Users}
alias Mobilizon.Actors.Actor alias Mobilizon.Actors.Actor
alias Mobilizon.Events.{Event, FeedToken} alias Mobilizon.Events.{Event, FeedToken}
alias Mobilizon.Posts.Post
alias Mobilizon.Storage.Page alias Mobilizon.Storage.Page
alias Mobilizon.Users.User alias Mobilizon.Users.User
@spec fetch_actor_event_feed(String.t(), integer()) :: String.t() @spec fetch_actor_event_feed(String.t(), integer()) ::
{:ok, Actor.t(), [Event.t()], [Post.t()]}
| {:error, :actor_not_public | :actor_not_found}
def fetch_actor_event_feed(name, limit) do def fetch_actor_event_feed(name, limit) do
with %Actor{} = actor <- Actors.get_actor_by_name(name), case Actors.get_actor_by_name(name) do
{:visibility, true} <- {:visibility, Actor.is_public_visibility?(actor)}, %Actor{} = actor ->
%Page{elements: events} <- Events.list_public_events_for_actor(actor, 1, limit), if Actor.is_public_visibility?(actor) do
%Page{elements: posts} <- Posts.get_public_posts_for_group(actor, 1, limit) do %Page{elements: events} = Events.list_public_events_for_actor(actor, 1, limit)
%Page{elements: posts} = Posts.get_public_posts_for_group(actor, 1, limit)
{:ok, actor, events, posts} {:ok, actor, events, posts}
else else
err -> {:error, :actor_not_public}
{:error, err} end
nil ->
{:error, :actor_not_found}
end end
end end
@typep token_feed_data :: %{
type: :actor | :user,
actor: Actor.t() | nil,
user: User.t(),
events: [Event.t()],
token: String.t()
}
# Only events, not posts # Only events, not posts
@spec fetch_events_from_token(String.t(), integer()) :: String.t() @spec fetch_events_from_token(String.t(), integer()) ::
token_feed_data | {:error, :bad_token | :token_not_found}
def fetch_events_from_token(token, limit) do def fetch_events_from_token(token, limit) do
with {:ok, uuid} <- ShortUUID.decode(token), case uuid_from_token(token) do
{:ok, _uuid} <- Ecto.UUID.cast(uuid), {:ok, uuid} ->
%FeedToken{actor: actor, user: %User{} = user} <- Events.get_feed_token(uuid) do case Events.get_feed_token(uuid) do
case actor do nil ->
%Actor{} = actor -> {:error, :token_not_found}
%FeedToken{actor: actor, user: %User{} = user} ->
produce_actor_feed(actor, user, token, limit)
end
{:error, :bad_token} ->
{:error, :bad_token}
end
end
@spec uuid_from_token(String.t()) :: {:ok, String.t()} | {:error, :bad_token}
defp uuid_from_token(token) do
case ShortUUID.decode(token) do
{:ok, uuid} ->
case Ecto.UUID.cast(uuid) do
{:ok, _uuid} ->
{:ok, uuid}
:error ->
{:error, :bad_token}
end
{:error, _err} ->
{:error, :bad_token}
end
end
@spec produce_actor_feed(Actor.t() | nil, User.t(), String.t(), integer()) :: token_feed_data
defp produce_actor_feed(%Actor{} = actor, %User{} = user, token, limit) do
%{ %{
type: :actor, type: :actor,
actor: actor, actor: actor,
@ -37,8 +82,9 @@ defmodule Mobilizon.Service.Export.Common do
user: user, user: user,
token: token token: token
} }
end
nil -> defp produce_actor_feed(nil, %User{} = user, token, limit) do
with actors <- Users.get_actors_for_user(user), with actors <- Users.get_actors_for_user(user),
events <- events <-
actors actors
@ -47,16 +93,13 @@ defmodule Mobilizon.Service.Export.Common do
%{type: :user, events: events, user: user, token: token, actor: nil} %{type: :user, events: events, user: user, token: token, actor: nil}
end end
end end
end
end
@spec fetch_instance_public_content(integer()) :: {:ok, list(Event.t()), list(Post.t())} @spec fetch_instance_public_content(integer()) :: {:ok, list(Event.t()), list(Post.t())}
def fetch_instance_public_content(limit) do def fetch_instance_public_content(limit) do
with %Page{elements: events} <- Events.list_public_local_events(1, limit), %Page{elements: events} = Events.list_public_local_events(1, limit)
%Page{elements: posts} <- Posts.list_public_local_posts(1, limit) do %Page{elements: posts} = Posts.list_public_local_posts(1, limit)
{:ok, events, posts} {:ok, events, posts}
end end
end
@spec fetch_actor_private_events(Actor.t(), integer()) :: list(Event.t()) @spec fetch_actor_private_events(Actor.t(), integer()) :: list(Event.t())
def fetch_actor_private_events(%Actor{} = actor, limit) do def fetch_actor_private_events(%Actor{} = actor, limit) do

View File

@ -96,13 +96,13 @@ defmodule Mobilizon.Service.Export.Feed do
{:ok, actor, events, posts} -> {:ok, actor, events, posts} ->
{:ok, build_actor_feed(actor, events, posts)} {:ok, build_actor_feed(actor, events, posts)}
err -> {:error, err} ->
{:error, err} {:error, err}
end end
end end
# Build an atom feed from actor and its public events and posts # Build an atom feed from actor and its public events and posts
@spec build_actor_feed(Actor.t(), list(), list(), boolean()) :: String.t() @spec build_actor_feed(Actor.t(), list(Event.t()), list(Post.t()), boolean()) :: String.t()
defp build_actor_feed(%Actor{} = actor, events, posts, public \\ true) do defp build_actor_feed(%Actor{} = actor, events, posts, public \\ true) do
display_name = Actor.display_name(actor) display_name = Actor.display_name(actor)
@ -199,19 +199,22 @@ defmodule Mobilizon.Service.Export.Feed do
end end
# Only events, not posts # Only events, not posts
@spec fetch_events_from_token(String.t()) :: String.t() @spec fetch_events_from_token(String.t(), integer()) :: {:ok, String.t()} | {:error, atom()}
defp fetch_events_from_token(token, limit \\ @item_limit) do defp fetch_events_from_token(token, limit \\ @item_limit) do
with %{events: events, token: token, user: user, actor: actor, type: type} <- case Common.fetch_events_from_token(token, limit) do
Common.fetch_events_from_token(token, limit) do %{events: events, token: token, user: user, actor: actor, type: type} ->
case type do case type do
:user -> {:ok, build_user_feed(events, user, token)} :user -> {:ok, build_user_feed(events, user, token)}
:actor -> {:ok, build_actor_feed(actor, events, [], false)} :actor -> {:ok, build_actor_feed(actor, events, [], false)}
end end
{:error, err} ->
{:error, err}
end end
end end
# Build an atom feed from actor and its public events # Build an atom feed from actor and its public events
@spec build_user_feed(list(), User.t(), String.t()) :: String.t() @spec build_user_feed(list(Event.t()), User.t(), String.t()) :: String.t()
defp build_user_feed(events, %User{email: email}, token) do defp build_user_feed(events, %User{email: email}, token) do
self_url = Endpoint |> Routes.feed_url(:going, token, "atom") |> URI.decode() self_url = Endpoint |> Routes.feed_url(:going, token, "atom") |> URI.decode()

View File

@ -15,12 +15,13 @@ defmodule Mobilizon.Service.Export.ICalendar do
@doc """ @doc """
Create cache for an actor, an event or an user token Create cache for an actor, an event or an user token
""" """
@spec create_cache(String.t()) :: {:commit, String.t()} | {:ignore, atom()}
def create_cache("actor_" <> name) do def create_cache("actor_" <> name) do
case export_public_actor(name) do case export_public_actor(name) do
{:ok, res} -> {:ok, res} ->
{:commit, res} {:commit, res}
err -> {:error, err} ->
{:ignore, err} {:ignore, err}
end end
end end
@ -30,8 +31,11 @@ defmodule Mobilizon.Service.Export.ICalendar do
{:ok, res} <- export_public_event(event) do {:ok, res} <- export_public_event(event) do
{:commit, res} {:commit, res}
else else
err -> {:error, err} ->
{:ignore, err} {:ignore, err}
nil ->
{:ignore, :event_not_found}
end end
end end
@ -40,30 +44,20 @@ defmodule Mobilizon.Service.Export.ICalendar do
{:ok, res} -> {:ok, res} ->
{:commit, res} {:commit, res}
err -> {:error, err} ->
{:ignore, err} {:ignore, err}
end end
end end
def create_cache("instance") do def create_cache("instance") do
case fetch_instance_feed() do {:ok, res} = fetch_instance_feed()
{:ok, res} ->
{:commit, res} {:commit, res}
err ->
{:ignore, err}
end
end end
@spec fetch_instance_feed :: {:ok, String.t()} @spec fetch_instance_feed :: {:ok, String.t()}
defp fetch_instance_feed do defp fetch_instance_feed do
case Common.fetch_instance_public_content(@item_limit) do {:ok, events, _posts} = Common.fetch_instance_public_content(@item_limit)
{:ok, events, _posts} ->
{:ok, %ICalendar{events: events |> Enum.map(&do_export_event/1)} |> ICalendar.to_ics()} {:ok, %ICalendar{events: events |> Enum.map(&do_export_event/1)} |> ICalendar.to_ics()}
err ->
{:error, err}
end
end end
@doc """ @doc """
@ -77,13 +71,12 @@ defmodule Mobilizon.Service.Export.ICalendar do
The event must have a visibility of `:public` or `:unlisted` The event must have a visibility of `:public` or `:unlisted`
""" """
@spec export_public_event(Event.t()) :: {:ok, String.t()} @spec export_public_event(Event.t()) :: {:ok, String.t()} | {:error, :event_not_public}
def export_public_event(%Event{visibility: visibility} = event) def export_public_event(%Event{visibility: visibility} = event)
when visibility in [:public, :unlisted] do when visibility in [:public, :unlisted] do
{:ok, events_to_ics([event])} {:ok, events_to_ics([event])}
end end
@spec export_public_event(Event.t()) :: {:error, :event_not_public}
def export_public_event(%Event{}), do: {:error, :event_not_public} def export_public_event(%Event{}), do: {:error, :event_not_public}
@doc """ @doc """
@ -91,28 +84,33 @@ defmodule Mobilizon.Service.Export.ICalendar do
The actor must have a visibility of `:public` or `:unlisted`, as well as the events The actor must have a visibility of `:public` or `:unlisted`, as well as the events
""" """
@spec export_public_actor(String.t()) :: String.t() @spec export_public_actor(String.t()) ::
{:ok, String.t()} | {:error, :actor_not_public | :actor_not_found}
def export_public_actor(name, limit \\ @item_limit) do def export_public_actor(name, limit \\ @item_limit) do
case Common.fetch_actor_event_feed(name, limit) do case Common.fetch_actor_event_feed(name, limit) do
{:ok, _actor, events, _posts} -> {:ok, _actor, events, _posts} ->
{:ok, events_to_ics(events)} {:ok, events_to_ics(events)}
err -> {:error, err} ->
{:error, err} {:error, err}
end end
end end
@spec export_private_actor(Actor.t()) :: String.t() @spec export_private_actor(Actor.t(), integer()) :: {:ok, String.t()}
def export_private_actor(%Actor{} = actor, limit \\ @item_limit) do def export_private_actor(%Actor{} = actor, limit \\ @item_limit) do
with events <- Common.fetch_actor_private_events(actor, limit) do events = Common.fetch_actor_private_events(actor, limit)
{:ok, events_to_ics(events)} {:ok, events_to_ics(events)}
end end
end
@spec fetch_events_from_token(String.t()) :: String.t() @spec fetch_events_from_token(String.t(), integer()) ::
{:ok, String.t()} | {:error, :actor_not_public | :actor_not_found}
defp fetch_events_from_token(token, limit \\ @item_limit) do defp fetch_events_from_token(token, limit \\ @item_limit) do
with %{events: events} <- Common.fetch_events_from_token(token, limit) do case Common.fetch_events_from_token(token, limit) do
%{events: events} ->
{:ok, events_to_ics(events)} {:ok, events_to_ics(events)}
{:error, err} ->
{:error, err}
end end
end end
@ -138,6 +136,7 @@ defmodule Mobilizon.Service.Export.ICalendar do
} }
end end
@spec vendor :: String.t()
defp vendor do defp vendor do
"Mobilizon #{Config.instance_version()}" "Mobilizon #{Config.instance_version()}"
end end

View File

@ -18,18 +18,20 @@ defmodule Mobilizon.Service.Formatter do
@link_regex ~r"((?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~%:/?#[\]@!\$&'\(\)\*\+,;=.]+)|[0-9a-z+\-\.]+:[0-9a-z$-_.+!*'(),]+"ui @link_regex ~r"((?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~%:/?#[\]@!\$&'\(\)\*\+,;=.]+)|[0-9a-z+\-\.]+:[0-9a-z$-_.+!*'(),]+"ui
@markdown_characters_regex ~r/(`|\*|_|{|}|[|]|\(|\)|#|\+|-|\.|!)/ @markdown_characters_regex ~r/(`|\*|_|{|}|[|]|\(|\)|#|\+|-|\.|!)/
def escape_mention_handler("@" <> nickname = mention, buffer, _, _) do @spec escape_mention_handler(String.t(), String.t(), any(), any()) :: String.t()
defp escape_mention_handler("@" <> nickname = mention, buffer, _, _) do
case Actors.get_actor_by_name(nickname) do case Actors.get_actor_by_name(nickname) do
%Actor{} -> %Actor{} ->
# escape markdown characters with `\\` # escape markdown characters with `\\`
# (we don't want something like @user__name to be parsed by markdown) # (we don't want something like @user__name to be parsed by markdown)
String.replace(mention, @markdown_characters_regex, "\\\\\\1") String.replace(mention, @markdown_characters_regex, "\\\\\\1")
_ -> nil ->
buffer buffer
end end
end end
@spec mention_handler(String.t(), String.t(), any(), map()) :: {String.t(), map()}
def mention_handler("@" <> nickname, buffer, _opts, acc) do def mention_handler("@" <> nickname, buffer, _opts, acc) do
case Actors.get_actor_by_name(nickname) do case Actors.get_actor_by_name(nickname) do
# %Actor{preferred_username: preferred_username} = actor -> # %Actor{preferred_username: preferred_username} = actor ->
@ -58,7 +60,7 @@ defmodule Mobilizon.Service.Formatter do
{link, %{acc | mentions: MapSet.put(acc.mentions, {"@" <> nickname, actor})}} {link, %{acc | mentions: MapSet.put(acc.mentions, {"@" <> nickname, actor})}}
_ -> nil ->
{buffer, acc} {buffer, acc}
end end
end end

View File

@ -14,6 +14,7 @@ defmodule Mobilizon.Service.Formatter.HTML do
def filter_tags(html), do: Sanitizer.scrub(html, DefaultScrubbler) def filter_tags(html), do: Sanitizer.scrub(html, DefaultScrubbler)
@spec strip_tags(String.t()) :: String.t() | no_return()
def strip_tags(html) do def strip_tags(html) do
case FastSanitize.strip_tags(html) do case FastSanitize.strip_tags(html) do
{:ok, html} -> {:ok, html} ->

View File

@ -93,7 +93,8 @@ defmodule Mobilizon.Service.Geospatial.Addok do
if is_nil(value), do: url, else: do_add_parameter(url, key, value) if is_nil(value), do: url, else: do_add_parameter(url, key, value)
end end
@spec do_add_parameter(String.t(), atom(), any()) :: String.t() @spec do_add_parameter(String.t(), :coords | :type, %{lat: float, lon: float} | :administrative) ::
String.t()
defp do_add_parameter(url, :coords, coords), defp do_add_parameter(url, :coords, coords),
do: "#{url}&lat=#{coords.lat}&lon=#{coords.lon}" do: "#{url}&lat=#{coords.lat}&lon=#{coords.lon}"

View File

@ -31,7 +31,7 @@ defmodule Mobilizon.Service.Geospatial.GoogleMaps do
@doc """ @doc """
Google Maps implementation for `c:Mobilizon.Service.Geospatial.Provider.geocode/3`. Google Maps implementation for `c:Mobilizon.Service.Geospatial.Provider.geocode/3`.
""" """
@spec geocode(String.t(), keyword()) :: list(Address.t()) @spec geocode(String.t(), keyword()) :: list(Address.t()) | no_return
def geocode(lon, lat, options \\ []) do def geocode(lon, lat, options \\ []) do
url = build_url(:geocode, %{lon: lon, lat: lat}, options) url = build_url(:geocode, %{lon: lon, lat: lat}, options)
@ -50,7 +50,7 @@ defmodule Mobilizon.Service.Geospatial.GoogleMaps do
@doc """ @doc """
Google Maps implementation for `c:Mobilizon.Service.Geospatial.Provider.search/2`. Google Maps implementation for `c:Mobilizon.Service.Geospatial.Provider.search/2`.
""" """
@spec search(String.t(), keyword()) :: list(Address.t()) @spec search(String.t(), keyword()) :: list(Address.t()) | no_return
def search(q, options \\ []) do def search(q, options \\ []) do
url = build_url(:search, %{q: q}, options) url = build_url(:search, %{q: q}, options)
@ -68,7 +68,7 @@ defmodule Mobilizon.Service.Geospatial.GoogleMaps do
end end
end end
@spec build_url(atom(), map(), list()) :: String.t() @spec build_url(atom(), map(), list()) :: String.t() | no_return
defp build_url(method, args, options) do defp build_url(method, args, options) do
limit = Keyword.get(options, :limit, 10) limit = Keyword.get(options, :limit, 10)
lang = Keyword.get(options, :lang, "en") lang = Keyword.get(options, :lang, "en")
@ -148,6 +148,7 @@ defmodule Mobilizon.Service.Geospatial.GoogleMaps do
end end
end end
@spec do_fetch_place_details(String.t() | nil, Keyword.t()) :: String.t() | no_return
defp do_fetch_place_details(place_id, options) do defp do_fetch_place_details(place_id, options) do
url = build_url(:place_details, %{place_id: place_id}, options) url = build_url(:place_details, %{place_id: place_id}, options)

View File

@ -42,7 +42,8 @@ defmodule Mobilizon.Service.Geospatial.Provider do
iex> geocode(48.11, -1.77) iex> geocode(48.11, -1.77)
%Address{} %Address{}
""" """
@callback geocode(longitude :: number, latitude :: number, options :: keyword) :: [Address.t()] @callback geocode(longitude :: number, latitude :: number, options :: keyword) ::
[Address.t()] | {:error, atom()}
@doc """ @doc """
Search for an address Search for an address
@ -62,12 +63,12 @@ defmodule Mobilizon.Service.Geospatial.Provider do
iex> search("10 rue Jangot") iex> search("10 rue Jangot")
%Address{} %Address{}
""" """
@callback search(address :: String.t(), options :: keyword) :: [Address.t()] @callback search(address :: String.t(), options :: keyword) :: [Address.t()] | {:error, atom()}
@doc """ @doc """
Returns a `Geo.Point` for given coordinates Returns a `Geo.Point` for given coordinates
""" """
@spec coordinates([number], number) :: Geo.Point.t() | nil @spec coordinates([number | String.t()], number) :: Geo.Point.t() | nil
def coordinates(coords, srid \\ 4326) def coordinates(coords, srid \\ 4326)
def coordinates([x, y], srid) when is_number(x) and is_number(y) do def coordinates([x, y], srid) when is_number(x) and is_number(y) do

View File

@ -12,7 +12,7 @@ defmodule Mobilizon.Service.Notifier.Email do
import Mobilizon.Service.DateTime, import Mobilizon.Service.DateTime,
only: [ only: [
is_delay_ok_since_last_notification_sent: 1 is_delay_ok_since_last_notification_sent?: 1
] ]
require Logger require Logger
@ -116,7 +116,7 @@ defmodule Mobilizon.Service.Notifier.Email do
# Delay ok since last notification # Delay ok since last notification
defp match_group_notifications_setting(:one_hour, _, %DateTime{} = last_notification_sent, _) do defp match_group_notifications_setting(:one_hour, _, %DateTime{} = last_notification_sent, _) do
is_delay_ok_since_last_notification_sent(last_notification_sent) is_delay_ok_since_last_notification_sent?(last_notification_sent)
end end
# This is a recap # This is a recap

View File

@ -66,12 +66,14 @@ defmodule Mobilizon.Service.Notifier.Push do
Map.get(@default_behavior, activity_setting, false) Map.get(@default_behavior, activity_setting, false)
end end
@spec send_subscription(Activity.t(), any, Keyword.t()) :: no_return
defp send_subscription(activity, subscription, options) do defp send_subscription(activity, subscription, options) do
activity activity
|> payload(options) |> payload(options)
|> WebPushEncryption.send_web_push(subscription) |> WebPushEncryption.send_web_push(subscription)
end end
@spec payload(Activity.t(), Keyword.t()) :: String.t()
defp payload(%Activity{} = activity, options) do defp payload(%Activity{} = activity, options) do
activity activity
|> Utils.add_activity_object() |> Utils.add_activity_object()

Some files were not shown because too many files have changed in this diff Show More