Fix credo style reports following it's update

Mainly transform `with` into `case`

Signed-off-by: Thomas Citharel <tcit@tcit.fr>
This commit is contained in:
Thomas Citharel 2019-07-23 18:06:22 +02:00
parent 1cd511f440
commit c3cca5d613
No known key found for this signature in database
GPG Key ID: A061B9DDE0CA0773
26 changed files with 303 additions and 248 deletions

View File

@ -10,11 +10,15 @@ defmodule Mix.Tasks.Mobilizon.Toot do
def run([from, content]) do def run([from, content]) do
Mix.Task.run("app.start") Mix.Task.run("app.start")
with {:ok, _} <- MobilizonWeb.API.Comments.create_comment(from, content) do case MobilizonWeb.API.Comments.create_comment(from, content) do
{:ok, _} ->
Mix.shell().info("Tooted") Mix.shell().info("Tooted")
else
{:local_actor, _} -> Mix.shell().error("Failed to toot.\nActor #{from} doesn't exist") {:local_actor, _} ->
_ -> Mix.shell().error("Failed to toot.") Mix.shell().error("Failed to toot.\nActor #{from} doesn't exist")
_ ->
Mix.shell().error("Failed to toot.")
end end
end end
end end

View File

@ -295,9 +295,10 @@ defmodule Mobilizon.Actors.Actor do
""" """
@spec prepare_public_key(String.t()) :: {:ok, tuple()} | {:error, :pem_decode_error} @spec prepare_public_key(String.t()) :: {:ok, tuple()} | {:error, :pem_decode_error}
def prepare_public_key(public_key_code) do def prepare_public_key(public_key_code) do
with [public_key_entry] <- :public_key.pem_decode(public_key_code) do case :public_key.pem_decode(public_key_code) do
[public_key_entry] ->
{:ok, :public_key.pem_entry_decode(public_key_entry)} {:ok, :public_key.pem_entry_decode(public_key_entry)}
else
_err -> _err ->
{:error, :pem_decode_error} {:error, :pem_decode_error}
end end
@ -423,10 +424,10 @@ defmodule Mobilizon.Actors.Actor do
""" """
@spec unfollow(struct(), struct()) :: {:ok, Follower.t()} | {:error, Ecto.Changeset.t()} @spec unfollow(struct(), struct()) :: {:ok, Follower.t()} | {:error, Ecto.Changeset.t()}
def unfollow(%Actor{} = followed, %Actor{} = follower) do def unfollow(%Actor{} = followed, %Actor{} = follower) do
with {:already_following, %Follower{} = follow} <- case {:already_following, following?(follower, followed)} do
{:already_following, following?(follower, followed)} do {:already_following, %Follower{} = follow} ->
Actors.delete_follower(follow) Actors.delete_follower(follow)
else
{:already_following, false} -> {:already_following, false} ->
{:error, "Could not unfollow actor: you are not following #{followed.preferred_username}"} {:error, "Could not unfollow actor: you are not following #{followed.preferred_username}"}
end end

View File

@ -281,8 +281,7 @@ defmodule Mobilizon.Actors do
data data
|> Actor.remote_actor_creation() |> Actor.remote_actor_creation()
with {:ok, actor} <- case Repo.insert(
Repo.insert(
cs, cs,
on_conflict: [ on_conflict: [
set: [ set: [
@ -293,9 +292,10 @@ defmodule Mobilizon.Actors do
], ],
conflict_target: [:url] conflict_target: [:url]
) do ) do
{:ok, actor} ->
actor = if preload, do: Repo.preload(actor, [:followers]), else: actor actor = if preload, do: Repo.preload(actor, [:followers]), else: actor
{:ok, actor} {:ok, actor}
else
err -> err ->
Logger.error(inspect(err)) Logger.error(inspect(err))
{:error, err} {:error, err}
@ -474,9 +474,10 @@ defmodule Mobilizon.Actors do
# TODO: Move this to Mobilizon.Service.ActivityPub # TODO: Move this to Mobilizon.Service.ActivityPub
@spec get_or_fetch_by_url(String.t(), bool()) :: {:ok, Actor.t()} | {:error, String.t()} @spec get_or_fetch_by_url(String.t(), bool()) :: {:ok, Actor.t()} | {:error, String.t()}
def get_or_fetch_by_url(url, preload \\ false) do def get_or_fetch_by_url(url, preload \\ false) do
with {:ok, actor} <- get_actor_by_url(url, preload) do case get_actor_by_url(url, preload) do
{:ok, actor} ->
{:ok, actor} {:ok, actor}
else
_ -> _ ->
case ActivityPub.make_actor_from_url(url, preload) do case ActivityPub.make_actor_from_url(url, preload) do
{:ok, actor} -> {:ok, actor} ->
@ -497,9 +498,10 @@ defmodule Mobilizon.Actors do
# TODO: Move this to Mobilizon.Service.ActivityPub # TODO: Move this to Mobilizon.Service.ActivityPub
@spec get_or_fetch_by_url!(String.t(), bool()) :: Actor.t() @spec get_or_fetch_by_url!(String.t(), bool()) :: Actor.t()
def get_or_fetch_by_url!(url, preload \\ false) do def get_or_fetch_by_url!(url, preload \\ false) do
with {:ok, actor} <- get_actor_by_url(url, preload) do case get_actor_by_url(url, preload) do
{:ok, actor} ->
actor actor
else
_ -> _ ->
case ActivityPub.make_actor_from_url(url, preload) do case ActivityPub.make_actor_from_url(url, preload) do
{:ok, actor} -> {:ok, actor} ->
@ -1001,9 +1003,10 @@ defmodule Mobilizon.Actors do
end end
defp safe_remove_file(url, %Actor{} = actor) do defp safe_remove_file(url, %Actor{} = actor) do
with {:ok, _value} <- MobilizonWeb.Upload.remove(url) do case MobilizonWeb.Upload.remove(url) do
{:ok, _value} ->
{:ok, actor} {:ok, actor}
else
{:error, error} -> {:error, error} ->
Logger.error("Error while removing an upload file") Logger.error("Error while removing an upload file")
Logger.error(inspect(error)) Logger.error(inspect(error))

View File

@ -187,10 +187,12 @@ defmodule Mobilizon.Events do
def get_cached_event_full_by_uuid(uuid) do def get_cached_event_full_by_uuid(uuid) do
Cachex.fetch(:activity_pub, "event_" <> uuid, fn "event_" <> uuid -> Cachex.fetch(:activity_pub, "event_" <> uuid, fn "event_" <> uuid ->
with %Event{} = event <- get_event_full_by_uuid(uuid) do case get_event_full_by_uuid(uuid) do
%Event{} = event ->
{:commit, event} {:commit, event}
else
_ -> {:ignore, nil} _ ->
{:ignore, nil}
end end
end) end)
end end
@ -1133,10 +1135,12 @@ defmodule Mobilizon.Events do
def get_cached_comment_full_by_uuid(uuid) do def get_cached_comment_full_by_uuid(uuid) do
Cachex.fetch(:activity_pub, "comment_" <> uuid, fn "comment_" <> uuid -> Cachex.fetch(:activity_pub, "comment_" <> uuid, fn "comment_" <> uuid ->
with %Comment{} = comment <- get_comment_full_from_uuid(uuid) do case get_comment_full_from_uuid(uuid) do
%Comment{} = comment ->
{:commit, comment} {:commit, comment}
else
_ -> {:ignore, nil} _ ->
{:ignore, nil}
end end
end) end)
end end

View File

@ -235,7 +235,8 @@ defmodule Mobilizon.Users do
end end
def update_user_default_actor(user_id, actor_id) do def update_user_default_actor(user_id, actor_id) do
with from(u in User, where: u.id == ^user_id, update: [set: [default_actor_id: ^actor_id]]) with _ <-
from(u in User, where: u.id == ^user_id, update: [set: [default_actor_id: ^actor_id]])
|> Repo.update_all([]) do |> Repo.update_all([]) do
Repo.get!(User, user_id) |> Repo.preload([:default_actor]) Repo.get!(User, user_id) |> Repo.preload([:default_actor])
end end

View File

@ -25,9 +25,10 @@ defmodule MobilizonWeb.API.Search do
# Some URLs could be domain.tld/@username, so keep this condition above handle_search? function # Some URLs could be domain.tld/@username, so keep this condition above handle_search? function
url_search?(search) -> url_search?(search) ->
# If this is not an actor, skip # If this is not an actor, skip
with %{:total => total, :elements => [%Actor{}] = elements} <- process_from_url(search) do case process_from_url(search) do
%{:total => total, :elements => [%Actor{}] = elements} ->
{:ok, %{total: total, elements: elements}} {:ok, %{total: total, elements: elements}}
else
_ -> _ ->
{:ok, %{total: 0, elements: []}} {:ok, %{total: 0, elements: []}}
end end
@ -55,9 +56,10 @@ defmodule MobilizonWeb.API.Search do
url_search?(search) -> url_search?(search) ->
# If this is not an event, skip # If this is not an event, skip
with {total = total, [%Event{} = elements]} <- process_from_url(search) do case process_from_url(search) do
{total = total, [%Event{} = elements]} ->
{:ok, %{total: total, elements: elements}} {:ok, %{total: total, elements: elements}}
else
_ -> _ ->
{:ok, %{total: 0, elements: []}} {:ok, %{total: 0, elements: []}}
end end
@ -70,9 +72,10 @@ defmodule MobilizonWeb.API.Search do
# If the search string is an username # If the search string is an username
@spec process_from_username(String.t()) :: %{total: integer(), elements: [Actor.t()]} @spec process_from_username(String.t()) :: %{total: integer(), elements: [Actor.t()]}
defp process_from_username(search) do defp process_from_username(search) do
with {:ok, actor} <- ActivityPub.find_or_make_actor_from_nickname(search) do case ActivityPub.find_or_make_actor_from_nickname(search) do
{:ok, actor} ->
%{total: 1, elements: [actor]} %{total: 1, elements: [actor]}
else
{:error, _err} -> {:error, _err} ->
Logger.debug(fn -> "Unable to find or make actor '#{search}'" end) Logger.debug(fn -> "Unable to find or make actor '#{search}'" end)
%{total: 0, elements: []} %{total: 0, elements: []}
@ -85,9 +88,10 @@ defmodule MobilizonWeb.API.Search do
elements: [Actor.t() | Event.t() | Comment.t()] elements: [Actor.t() | Event.t() | Comment.t()]
} }
defp process_from_url(search) do defp process_from_url(search) do
with {:ok, object} <- ActivityPub.fetch_object_from_url(search) do case ActivityPub.fetch_object_from_url(search) do
{:ok, object} ->
%{total: 1, elements: [object]} %{total: 1, elements: [object]}
else
{:error, _err} -> {:error, _err} ->
Logger.debug(fn -> "Unable to find or make object from URL '#{search}'" end) Logger.debug(fn -> "Unable to find or make object from URL '#{search}'" end)
%{total: 0, elements: []} %{total: 0, elements: []}

View File

@ -15,7 +15,7 @@ defmodule MobilizonWeb.ActivityPubController do
action_fallback(:errors) action_fallback(:errors)
def following(conn, %{"name" => name, "page" => page}) do def following(conn, %{"name" => name, "page" => page}) do
with {page, ""} = Integer.parse(page), with {page, ""} <- Integer.parse(page),
%Actor{} = actor <- Actors.get_local_actor_by_name_with_everything(name) do %Actor{} = actor <- Actors.get_local_actor_by_name_with_everything(name) do
conn conn
|> put_resp_header("content-type", "application/activity+json") |> put_resp_header("content-type", "application/activity+json")
@ -32,7 +32,7 @@ defmodule MobilizonWeb.ActivityPubController do
end end
def followers(conn, %{"name" => name, "page" => page}) do def followers(conn, %{"name" => name, "page" => page}) do
with {page, ""} = Integer.parse(page), with {page, ""} <- Integer.parse(page),
%Actor{} = actor <- Actors.get_local_actor_by_name_with_everything(name) do %Actor{} = actor <- Actors.get_local_actor_by_name_with_everything(name) do
conn conn
|> put_resp_header("content-type", "application/activity+json") |> put_resp_header("content-type", "application/activity+json")
@ -49,7 +49,7 @@ defmodule MobilizonWeb.ActivityPubController do
end end
def outbox(conn, %{"name" => name, "page" => page}) do def outbox(conn, %{"name" => name, "page" => page}) do
with {page, ""} = Integer.parse(page), with {page, ""} <- Integer.parse(page),
%Actor{} = actor <- Actors.get_local_actor_by_name(name) do %Actor{} = actor <- Actors.get_local_actor_by_name(name) do
conn conn
|> put_resp_header("content-type", "application/activity+json") |> put_resp_header("content-type", "application/activity+json")

View File

@ -7,60 +7,60 @@ defmodule MobilizonWeb.FeedController do
action_fallback(MobilizonWeb.FallbackController) action_fallback(MobilizonWeb.FallbackController)
def actor(conn, %{"name" => name, "format" => "atom"}) do def actor(conn, %{"name" => name, "format" => "atom"}) do
with {status, data} when status in [:ok, :commit] <- case Cachex.fetch(:feed, "actor_" <> name) do
Cachex.fetch(:feed, "actor_" <> name) do {status, data} when status in [:ok, :commit] ->
conn conn
|> put_resp_content_type("application/atom+xml") |> put_resp_content_type("application/atom+xml")
|> send_resp(200, data) |> send_resp(200, data)
else
_err -> _err ->
{:error, :not_found} {:error, :not_found}
end end
end end
def actor(conn, %{"name" => name, "format" => "ics"}) do def actor(conn, %{"name" => name, "format" => "ics"}) do
with {status, data} when status in [:ok, :commit] <- case Cachex.fetch(:ics, "actor_" <> name) do
Cachex.fetch(:ics, "actor_" <> name) do {status, data} when status in [:ok, :commit] ->
conn conn
|> put_resp_content_type("text/calendar") |> put_resp_content_type("text/calendar")
|> send_resp(200, data) |> send_resp(200, data)
else
_err -> _err ->
{:error, :not_found} {:error, :not_found}
end end
end end
def event(conn, %{"uuid" => uuid, "format" => "ics"}) do def event(conn, %{"uuid" => uuid, "format" => "ics"}) do
with {status, data} when status in [:ok, :commit] <- case Cachex.fetch(:ics, "event_" <> uuid) do
Cachex.fetch(:ics, "event_" <> uuid) do {status, data} when status in [:ok, :commit] ->
conn conn
|> put_resp_content_type("text/calendar") |> put_resp_content_type("text/calendar")
|> send_resp(200, data) |> send_resp(200, data)
else
_err -> _err ->
{:error, :not_found} {:error, :not_found}
end end
end end
def going(conn, %{"token" => token, "format" => "ics"}) do def going(conn, %{"token" => token, "format" => "ics"}) do
with {status, data} when status in [:ok, :commit] <- case Cachex.fetch(:ics, "token_" <> token) do
Cachex.fetch(:ics, "token_" <> token) do {status, data} when status in [:ok, :commit] ->
conn conn
|> put_resp_content_type("text/calendar") |> put_resp_content_type("text/calendar")
|> send_resp(200, data) |> send_resp(200, data)
else
_err -> _err ->
{:error, :not_found} {:error, :not_found}
end end
end end
def going(conn, %{"token" => token, "format" => "atom"}) do def going(conn, %{"token" => token, "format" => "atom"}) do
with {status, data} when status in [:ok, :commit] <- case Cachex.fetch(:feed, "token_" <> token) do
Cachex.fetch(:feed, "token_" <> token) do {status, data} when status in [:ok, :commit] ->
conn conn
|> put_resp_content_type("application/atom+xml") |> put_resp_content_type("application/atom+xml")
|> send_resp(200, data) |> send_resp(200, data)
else
_err -> _err ->
{:error, :not_found} {:error, :not_found}
end end

View File

@ -176,11 +176,12 @@ defmodule MobilizonWeb.Resolvers.Event do
# and that it's the actor requesting leaving the event we return true # and that it's the actor requesting leaving the event we return true
@spec check_that_participant_is_not_only_organizer(integer(), integer()) :: boolean() @spec check_that_participant_is_not_only_organizer(integer(), integer()) :: boolean()
defp check_that_participant_is_not_only_organizer(event_id, actor_id) do defp check_that_participant_is_not_only_organizer(event_id, actor_id) do
with [%Participant{actor: %Actor{id: participant_actor_id}}] <- case Mobilizon.Events.list_organizers_participants_for_event(event_id) do
Mobilizon.Events.list_organizers_participants_for_event(event_id) do [%Participant{actor: %Actor{id: participant_actor_id}}] ->
participant_actor_id == actor_id participant_actor_id == actor_id
else
_ -> false _ ->
false
end end
end end

View File

@ -218,17 +218,18 @@ defmodule MobilizonWeb.Resolvers.Group do
# and that it's the actor requesting leaving the group we return true # and that it's the actor requesting leaving the group we return true
@spec check_that_member_is_not_only_administrator(integer(), integer()) :: boolean() @spec check_that_member_is_not_only_administrator(integer(), integer()) :: boolean()
defp check_that_member_is_not_only_administrator(group_id, actor_id) do defp check_that_member_is_not_only_administrator(group_id, actor_id) do
with [ case Member.list_administrator_members_for_group(group_id) do
[
%Member{ %Member{
actor: %Actor{ actor: %Actor{
id: member_actor_id id: member_actor_id
} }
} }
] <- ] ->
Member.list_administrator_members_for_group(group_id) do
actor_id == member_actor_id actor_id == member_actor_id
else
_ -> false _ ->
false
end end
end end
end end

View File

@ -35,10 +35,17 @@ defmodule MobilizonWeb.Resolvers.Picture do
@spec do_fetch_picture(String.t()) :: {:ok, Picture.t()} | {:error, :not_found} @spec do_fetch_picture(String.t()) :: {:ok, Picture.t()} | {:error, :not_found}
defp do_fetch_picture(picture_id) do defp do_fetch_picture(picture_id) do
with %Picture{id: id, file: file} = _pic <- Media.get_picture(picture_id) do case Media.get_picture(picture_id) do
%Picture{id: id, file: file} = _pic ->
{:ok, {:ok,
%{name: file.name, url: file.url, id: id, content_type: file.content_type, size: file.size}} %{
else name: file.name,
url: file.url,
id: id,
content_type: file.content_type,
size: file.size
}}
_err -> _err ->
{:error, "Picture with ID #{picture_id} was not found"} {:error, "Picture with ID #{picture_id} was not found"}
end end

View File

@ -94,7 +94,9 @@ defmodule MobilizonWeb.Upload do
{:same_host, true} <- {:same_host, host == MobilizonWeb.Endpoint.host()} do {:same_host, true} <- {:same_host, host == MobilizonWeb.Endpoint.host()} do
MobilizonWeb.Uploaders.Uploader.remove_file(opts.uploader, path) MobilizonWeb.Uploaders.Uploader.remove_file(opts.uploader, path)
else else
%URI{} = _uri -> {:error, "URL doesn't match pattern"} %URI{} = _uri ->
{:error, "URL doesn't match pattern"}
{:same_host, _} -> {:same_host, _} ->
Logger.error("Media can't be deleted because its URL doesn't match current host") Logger.error("Media can't be deleted because its URL doesn't match current host")
end end

View File

@ -289,7 +289,7 @@ defmodule Mobilizon.Service.ActivityPub do
"to" => [actor.url <> "/followers", "https://www.w3.org/ns/activitystreams#Public"] "to" => [actor.url <> "/followers", "https://www.w3.org/ns/activitystreams#Public"]
} }
with Events.delete_event(event), with {:ok, _} <- Events.delete_event(event),
{:ok, activity, _object} <- insert(data, local), {:ok, activity, _object} <- insert(data, local),
:ok <- maybe_federate(activity) do :ok <- maybe_federate(activity) do
{:ok, activity} {:ok, activity}
@ -304,7 +304,7 @@ defmodule Mobilizon.Service.ActivityPub do
"to" => [actor.url <> "/followers", "https://www.w3.org/ns/activitystreams#Public"] "to" => [actor.url <> "/followers", "https://www.w3.org/ns/activitystreams#Public"]
} }
with Events.delete_comment(comment), with {:ok, _} <- Events.delete_comment(comment),
{:ok, activity, _object} <- insert(data, local), {:ok, activity, _object} <- insert(data, local),
:ok <- maybe_federate(activity) do :ok <- maybe_federate(activity) do
{:ok, activity} {:ok, activity}
@ -319,7 +319,7 @@ defmodule Mobilizon.Service.ActivityPub do
"to" => [url <> "/followers", "https://www.w3.org/ns/activitystreams#Public"] "to" => [url <> "/followers", "https://www.w3.org/ns/activitystreams#Public"]
} }
with Actors.delete_actor(actor), with {:ok, _} <- Actors.delete_actor(actor),
{:ok, activity, _object} <- insert(data, local), {:ok, activity, _object} <- insert(data, local),
:ok <- maybe_federate(activity) do :ok <- maybe_federate(activity) do
{:ok, activity} {:ok, activity}
@ -352,9 +352,10 @@ defmodule Mobilizon.Service.ActivityPub do
""" """
@spec make_actor_from_url(String.t(), boolean()) :: {:ok, %Actor{}} | {:error, any()} @spec make_actor_from_url(String.t(), boolean()) :: {:ok, %Actor{}} | {:error, any()}
def make_actor_from_url(url, preload \\ false) do def make_actor_from_url(url, preload \\ false) do
with {:ok, data} <- fetch_and_prepare_actor_from_url(url) do case fetch_and_prepare_actor_from_url(url) do
{:ok, data} ->
Actors.insert_or_update_actor(data, preload) Actors.insert_or_update_actor(data, preload)
else
# Request returned 410 # Request returned 410
{:error, :actor_deleted} -> {:error, :actor_deleted} ->
{:error, :actor_deleted} {:error, :actor_deleted}
@ -371,10 +372,12 @@ defmodule Mobilizon.Service.ActivityPub do
""" """
@spec find_or_make_actor_from_nickname(String.t(), atom() | nil) :: tuple() @spec find_or_make_actor_from_nickname(String.t(), atom() | nil) :: tuple()
def find_or_make_actor_from_nickname(nickname, type \\ nil) do def find_or_make_actor_from_nickname(nickname, type \\ nil) do
with %Actor{} = actor <- Actors.get_actor_by_name(nickname, type) do case Actors.get_actor_by_name(nickname, type) do
%Actor{} = actor ->
{:ok, actor} {:ok, actor}
else
nil -> make_actor_from_nickname(nickname) nil ->
make_actor_from_nickname(nickname)
end end
end end
@ -389,10 +392,12 @@ defmodule Mobilizon.Service.ActivityPub do
""" """
@spec make_actor_from_nickname(String.t()) :: {:ok, %Actor{}} | {:error, any()} @spec make_actor_from_nickname(String.t()) :: {:ok, %Actor{}} | {:error, any()}
def make_actor_from_nickname(nickname) do def make_actor_from_nickname(nickname) do
with {:ok, %{"url" => url}} when not is_nil(url) <- WebFinger.finger(nickname) do case WebFinger.finger(nickname) do
{:ok, %{"url" => url}} when not is_nil(url) ->
make_actor_from_url(url) make_actor_from_url(url)
else
_e -> {:error, "No ActivityPub URL found in WebFinger"} _e ->
{:error, "No ActivityPub URL found in WebFinger"}
end end
end end

View File

@ -37,18 +37,22 @@ defmodule Mobilizon.Service.ActivityPub.Converters.Flag do
with {:ok, %Actor{} = reporter} <- Actors.get_actor_by_url(object["actor"]), with {:ok, %Actor{} = reporter} <- Actors.get_actor_by_url(object["actor"]),
%Actor{} = reported <- %Actor{} = reported <-
Enum.reduce_while(objects, nil, fn url, _ -> Enum.reduce_while(objects, nil, fn url, _ ->
with {:ok, %Actor{} = actor} <- Actors.get_actor_by_url(url) do case Actors.get_actor_by_url(url) do
{:ok, %Actor{} = actor} ->
{:halt, actor} {:halt, actor}
else
_ -> {:cont, nil} _ ->
{:cont, nil}
end end
end), end),
event <- event <-
Enum.reduce_while(objects, nil, fn url, _ -> Enum.reduce_while(objects, nil, fn url, _ ->
with %Event{} = event <- Events.get_event_by_url(url) do case Events.get_event_by_url(url) do
%Event{} = event ->
{:halt, event} {:halt, event}
else
_ -> {:cont, nil} _ ->
{:cont, nil}
end end
end), end),

View File

@ -209,7 +209,8 @@ defmodule Mobilizon.Service.ActivityPub.Transmogrifier do
data data
) )
when object_type in ["Person", "Application", "Service", "Organization"] do when object_type in ["Person", "Application", "Service", "Organization"] do
with {:ok, %Actor{url: url}} <- Actors.get_actor_by_url(object["id"]) do case Actors.get_actor_by_url(object["id"]) do
{:ok, %Actor{url: url}} ->
{:ok, new_actor_data} = ActivityPub.actor_data_from_actor_object(object) {:ok, new_actor_data} = ActivityPub.actor_data_from_actor_object(object)
Actors.insert_or_update_actor(new_actor_data) Actors.insert_or_update_actor(new_actor_data)
@ -221,7 +222,7 @@ defmodule Mobilizon.Service.ActivityPub.Transmogrifier do
object: object, object: object,
actor: url actor: url
}) })
else
e -> e ->
Logger.error(inspect(e)) Logger.error(inspect(e))
:error :error

View File

@ -206,10 +206,12 @@ defmodule Mobilizon.Service.ActivityPub.Utils do
Save picture data from %Plug.Upload{} and return AS Link data. Save picture data from %Plug.Upload{} and return AS Link data.
""" """
def make_picture_data(%Plug.Upload{} = picture) do def make_picture_data(%Plug.Upload{} = picture) do
with {:ok, picture} <- MobilizonWeb.Upload.store(picture) do case MobilizonWeb.Upload.store(picture) do
{:ok, picture} ->
picture picture
else
_ -> nil _ ->
nil
end end
end end

View File

@ -21,9 +21,10 @@ defmodule Mobilizon.Service.Export.Feed do
@spec create_cache(String.t()) :: {:commit, String.t()} | {:ignore, any()} @spec create_cache(String.t()) :: {:commit, String.t()} | {:ignore, any()}
def create_cache("actor_" <> name) do def create_cache("actor_" <> name) do
with {:ok, res} <- fetch_actor_event_feed(name) do case fetch_actor_event_feed(name) do
{:ok, res} ->
{:commit, res} {:commit, res}
else
err -> err ->
{:ignore, err} {:ignore, err}
end end
@ -31,9 +32,10 @@ defmodule Mobilizon.Service.Export.Feed do
@spec create_cache(String.t()) :: {:commit, String.t()} | {:ignore, any()} @spec create_cache(String.t()) :: {:commit, String.t()} | {:ignore, any()}
def create_cache("token_" <> token) do def create_cache("token_" <> token) do
with {:ok, res} <- fetch_events_from_token(token) do case fetch_events_from_token(token) do
{:ok, res} ->
{:commit, res} {:commit, res}
else
err -> err ->
{:ignore, err} {:ignore, err}
end end
@ -99,7 +101,8 @@ defmodule Mobilizon.Service.Export.Feed do
defp get_entry(%Event{} = event) do defp get_entry(%Event{} = event) do
description = event.description || "" description = event.description || ""
with {:ok, html, []} <- Earmark.as_html(description) do case Earmark.as_html(description) do
{:ok, html, []} ->
entry = entry =
Entry.new(event.url, event.publish_at || event.inserted_at, event.title) Entry.new(event.url, event.publish_at || event.inserted_at, event.title)
|> Entry.link(event.url, rel: "alternate", type: "text/html") |> Entry.link(event.url, rel: "alternate", type: "text/html")
@ -113,7 +116,7 @@ defmodule Mobilizon.Service.Export.Feed do
|> Enum.reduce(entry, fn tag, acc -> Entry.category(acc, tag.slug, label: tag.title) end) |> Enum.reduce(entry, fn tag, acc -> Entry.category(acc, tag.slug, label: tag.title) end)
Entry.build(entry) Entry.build(entry)
else
{:error, _html, error_messages} -> {:error, _html, error_messages} ->
Logger.error("Unable to produce HTML for Markdown", details: inspect(error_messages)) Logger.error("Unable to produce HTML for Markdown", details: inspect(error_messages))
end end

View File

@ -87,9 +87,10 @@ defmodule Mobilizon.Service.Export.ICalendar do
Create cache for an actor Create cache for an actor
""" """
def create_cache("token_" <> token) do def create_cache("token_" <> token) do
with {:ok, res} <- fetch_events_from_token(token) do case fetch_events_from_token(token) do
{:ok, res} ->
{:commit, res} {:commit, res}
else
err -> err ->
{:ignore, err} {:ignore, err}
end end

View File

@ -51,8 +51,10 @@ defmodule Mobilizon.Service.Federator do
Logger.info("Handling incoming AP activity") Logger.info("Handling incoming AP activity")
Logger.debug(inspect(params)) Logger.debug(inspect(params))
with {:ok, _activity} <- Transmogrifier.handle_incoming(params) do case Transmogrifier.handle_incoming(params) do
else {:ok, activity} ->
{:ok, activity}
%Activity{} -> %Activity{} ->
Logger.info("Already had #{params["id"]}") Logger.info("Already had #{params["id"]}")

View File

@ -23,7 +23,7 @@ defmodule Mobilizon.Service.Geospatial.Addok do
with {:ok, %HTTPoison.Response{status_code: 200, body: body}} <- with {:ok, %HTTPoison.Response{status_code: 200, body: body}} <-
HTTPoison.get(url), HTTPoison.get(url),
{:ok, %{"features" => features}} <- Poison.decode(body) do {:ok, %{"features" => features}} <- Poison.decode(body) do
processData(features) process_data(features)
end end
end end
@ -39,7 +39,7 @@ defmodule Mobilizon.Service.Geospatial.Addok do
with {:ok, %HTTPoison.Response{status_code: 200, body: body}} <- with {:ok, %HTTPoison.Response{status_code: 200, body: body}} <-
HTTPoison.get(url), HTTPoison.get(url),
{:ok, %{"features" => features}} <- Poison.decode(body) do {:ok, %{"features" => features}} <- Poison.decode(body) do
processData(features) process_data(features)
end end
end end
@ -59,23 +59,23 @@ defmodule Mobilizon.Service.Geospatial.Addok do
end end
end end
defp processData(features) do defp process_data(features) do
features features
|> Enum.map(fn %{"geometry" => geometry, "properties" => properties} -> |> Enum.map(fn %{"geometry" => geometry, "properties" => properties} ->
%Address{ %Address{
country: Map.get(properties, "country"), country: Map.get(properties, "country"),
locality: Map.get(properties, "city"), locality: Map.get(properties, "city"),
region: Map.get(properties, "state"), region: Map.get(properties, "state"),
description: Map.get(properties, "name") || streetAddress(properties), description: Map.get(properties, "name") || street_address(properties),
floor: Map.get(properties, "floor"), floor: Map.get(properties, "floor"),
geom: Map.get(geometry, "coordinates") |> Provider.coordinates(), geom: Map.get(geometry, "coordinates") |> Provider.coordinates(),
postal_code: Map.get(properties, "postcode"), postal_code: Map.get(properties, "postcode"),
street: properties |> streetAddress() street: properties |> street_address()
} }
end) end)
end end
defp streetAddress(properties) do defp street_address(properties) do
if Map.has_key?(properties, "housenumber") do if Map.has_key?(properties, "housenumber") do
Map.get(properties, "housenumber") <> " " <> Map.get(properties, "street") Map.get(properties, "housenumber") <> " " <> Map.get(properties, "street")
else else

View File

@ -39,7 +39,7 @@ defmodule Mobilizon.Service.Geospatial.MapQuest do
},#{lon}&maxResults=#{limit}" },#{lon}&maxResults=#{limit}"
), ),
{:ok, %{"results" => results, "info" => %{"statuscode" => 0}}} <- Poison.decode(body) do {:ok, %{"results" => results, "info" => %{"statuscode" => 0}}} <- Poison.decode(body) do
results |> Enum.map(&processData/1) results |> Enum.map(&process_data/1)
else else
{:ok, %HTTPoison.Response{status_code: 403, body: err}} -> {:ok, %HTTPoison.Response{status_code: 403, body: err}} ->
raise(ArgumentError, message: err) raise(ArgumentError, message: err)
@ -71,14 +71,14 @@ defmodule Mobilizon.Service.Geospatial.MapQuest do
with {:ok, %HTTPoison.Response{status_code: 200, body: body}} <- with {:ok, %HTTPoison.Response{status_code: 200, body: body}} <-
HTTPoison.get(url), HTTPoison.get(url),
{:ok, %{"results" => results, "info" => %{"statuscode" => 0}}} <- Poison.decode(body) do {:ok, %{"results" => results, "info" => %{"statuscode" => 0}}} <- Poison.decode(body) do
results |> Enum.map(&processData/1) results |> Enum.map(&process_data/1)
else else
{:ok, %HTTPoison.Response{status_code: 403, body: err}} -> {:ok, %HTTPoison.Response{status_code: 403, body: err}} ->
raise(ArgumentError, message: err) raise(ArgumentError, message: err)
end end
end end
defp processData( defp process_data(
%{ %{
"locations" => addresses, "locations" => addresses,
"providedLocation" => %{"latLng" => %{"lat" => lat, "lng" => lng}} "providedLocation" => %{"latLng" => %{"lat" => lat, "lng" => lng}}
@ -86,22 +86,22 @@ defmodule Mobilizon.Service.Geospatial.MapQuest do
) do ) do
case addresses do case addresses do
[] -> nil [] -> nil
addresses -> addresses |> hd |> produceAddress(lat, lng) addresses -> addresses |> hd |> produce_address(lat, lng)
end end
end end
defp processData(%{"locations" => addresses}) do defp process_data(%{"locations" => addresses}) do
case addresses do case addresses do
[] -> nil [] -> nil
addresses -> addresses |> hd |> produceAddress() addresses -> addresses |> hd |> produce_address()
end end
end end
defp produceAddress(%{"latLng" => %{"lat" => lat, "lng" => lng}} = address) do defp produce_address(%{"latLng" => %{"lat" => lat, "lng" => lng}} = address) do
produceAddress(address, lat, lng) produce_address(address, lat, lng)
end end
defp produceAddress(address, lat, lng) do defp produce_address(address, lat, lng) do
%Address{ %Address{
country: Map.get(address, "adminArea1"), country: Map.get(address, "adminArea1"),
locality: Map.get(address, "adminArea5"), locality: Map.get(address, "adminArea5"),

View File

@ -24,7 +24,7 @@ defmodule Mobilizon.Service.Geospatial.Photon do
with {:ok, %HTTPoison.Response{status_code: 200, body: body}} <- with {:ok, %HTTPoison.Response{status_code: 200, body: body}} <-
HTTPoison.get(url), HTTPoison.get(url),
{:ok, %{"features" => features}} <- Poison.decode(body) do {:ok, %{"features" => features}} <- Poison.decode(body) do
processData(features) process_data(features)
end end
end end
@ -40,7 +40,7 @@ defmodule Mobilizon.Service.Geospatial.Photon do
with {:ok, %HTTPoison.Response{status_code: 200, body: body}} <- with {:ok, %HTTPoison.Response{status_code: 200, body: body}} <-
HTTPoison.get(url), HTTPoison.get(url),
{:ok, %{"features" => features}} <- Poison.decode(body) do {:ok, %{"features" => features}} <- Poison.decode(body) do
processData(features) process_data(features)
end end
end end
@ -61,23 +61,23 @@ defmodule Mobilizon.Service.Geospatial.Photon do
end end
end end
defp processData(features) do defp process_data(features) do
features features
|> Enum.map(fn %{"geometry" => geometry, "properties" => properties} -> |> Enum.map(fn %{"geometry" => geometry, "properties" => properties} ->
%Address{ %Address{
country: Map.get(properties, "country"), country: Map.get(properties, "country"),
locality: Map.get(properties, "city"), locality: Map.get(properties, "city"),
region: Map.get(properties, "state"), region: Map.get(properties, "state"),
description: Map.get(properties, "name") || streetAddress(properties), description: Map.get(properties, "name") || street_address(properties),
floor: Map.get(properties, "floor"), floor: Map.get(properties, "floor"),
geom: Map.get(geometry, "coordinates") |> Provider.coordinates(), geom: Map.get(geometry, "coordinates") |> Provider.coordinates(),
postal_code: Map.get(properties, "postcode"), postal_code: Map.get(properties, "postcode"),
street: properties |> streetAddress() street: properties |> street_address()
} }
end) end)
end end
defp streetAddress(properties) do defp street_address(properties) do
if Map.has_key?(properties, "housenumber") do if Map.has_key?(properties, "housenumber") do
Map.get(properties, "housenumber") <> " " <> Map.get(properties, "street") Map.get(properties, "housenumber") <> " " <> Map.get(properties, "street")
else else

View File

@ -49,10 +49,10 @@ defmodule Mobilizon.Service.HTTPSignatures do
def validate_conn(conn) do def validate_conn(conn) do
# TODO: How to get the right key and see if it is actually valid for that request. # TODO: How to get the right key and see if it is actually valid for that request.
# For now, fetch the key for the actor. # For now, fetch the key for the actor.
with {:ok, public_key} <- conn.params["actor"] |> Actor.get_public_key_for_url() do case conn.params["actor"] |> Actor.get_public_key_for_url() do
{:ok, public_key} ->
if validate_conn(conn, public_key) do if validate_conn(conn, public_key) do
true true
else
Logger.info("Could not validate request, re-fetching user and trying one more time") Logger.info("Could not validate request, re-fetching user and trying one more time")
# Fetch user anew and try one more time # Fetch user anew and try one more time
with actor_id <- conn.params["actor"], with actor_id <- conn.params["actor"],
@ -61,7 +61,7 @@ defmodule Mobilizon.Service.HTTPSignatures do
validate_conn(conn, public_key) validate_conn(conn, public_key)
end end
end end
else
e -> e ->
Logger.debug("Could not found url for actor!") Logger.debug("Could not found url for actor!")
Logger.debug(inspect(e)) Logger.debug(inspect(e))
@ -104,9 +104,10 @@ defmodule Mobilizon.Service.HTTPSignatures do
end end
def generate_date_header(date \\ Timex.now("GMT")) do def generate_date_header(date \\ Timex.now("GMT")) do
with {:ok, date} <- Timex.format(date, "%a, %d %b %Y %H:%M:%S %Z", :strftime) do case Timex.format(date, "%a, %d %b %Y %H:%M:%S %Z", :strftime) do
{:ok, date} ->
date date
else
{:error, err} -> {:error, err} ->
Logger.error("Unable to generate date header") Logger.error("Unable to generate date header")
Logger.error(inspect(err)) Logger.error(inspect(err))

View File

@ -43,9 +43,10 @@ defmodule Mobilizon.Service.WebFinger do
{:ok, represent_actor(actor, "JSON")} {:ok, represent_actor(actor, "JSON")}
else else
_e -> _e ->
with {:ok, %Actor{} = actor} when not is_nil(actor) <- Actors.get_actor_by_url(resource) do case Actors.get_actor_by_url(resource) do
{:ok, %Actor{} = actor} when not is_nil(actor) ->
{:ok, represent_actor(actor, "JSON")} {:ok, represent_actor(actor, "JSON")}
else
_e -> _e ->
{:error, "Couldn't find actor"} {:error, "Couldn't find actor"}
end end
@ -94,9 +95,10 @@ defmodule Mobilizon.Service.WebFinger do
actor = String.trim_leading(actor, "@") actor = String.trim_leading(actor, "@")
domain = domain =
with [_name, domain] <- String.split(actor, "@") do case String.split(actor, "@") do
[_name, domain] ->
domain domain
else
_e -> _e ->
URI.parse(actor).host URI.parse(actor).host
end end

View File

@ -440,9 +440,10 @@ defmodule Mobilizon.ActorsTest do
end end
test "create_bot/1 with invalid data returns error changeset" do test "create_bot/1 with invalid data returns error changeset" do
with {:error, %Ecto.Changeset{}} <- Actors.create_bot(@invalid_attrs) do case Actors.create_bot(@invalid_attrs) do
{:error, %Ecto.Changeset{}} ->
assert true assert true
else
_ -> _ ->
assert false assert false
end end

View File

@ -92,12 +92,13 @@ defmodule Mobilizon.EventsTest do
|> Map.put(:organizer_actor_id, actor.id) |> Map.put(:organizer_actor_id, actor.id)
|> Map.put(:address_id, address.id) |> Map.put(:address_id, address.id)
with {:ok, %Event{} = event} <- Events.create_event(valid_attrs) do case Events.create_event(valid_attrs) do
{:ok, %Event{} = event} ->
assert event.begins_on == DateTime.from_naive!(~N[2010-04-17 14:00:00Z], "Etc/UTC") assert event.begins_on == DateTime.from_naive!(~N[2010-04-17 14:00:00Z], "Etc/UTC")
assert event.description == "some description" assert event.description == "some description"
assert event.ends_on == DateTime.from_naive!(~N[2010-04-17 14:00:00Z], "Etc/UTC") assert event.ends_on == DateTime.from_naive!(~N[2010-04-17 14:00:00Z], "Etc/UTC")
assert event.title == "some title" assert event.title == "some title"
else
err -> err ->
flunk("Failed to create an event #{inspect(err)}") flunk("Failed to create an event #{inspect(err)}")
end end
@ -138,10 +139,11 @@ defmodule Mobilizon.EventsTest do
test "get_public_events_for_actor/3", %{actor: actor, event: event} do test "get_public_events_for_actor/3", %{actor: actor, event: event} do
event1 = insert(:event, organizer_actor: actor) event1 = insert(:event, organizer_actor: actor)
with {:ok, events_found, 2} <- Events.get_public_events_for_actor(actor, 1, 10) do case Events.get_public_events_for_actor(actor, 1, 10) do
{:ok, events_found, 2} ->
event_ids = MapSet.new(events_found |> Enum.map(& &1.id)) event_ids = MapSet.new(events_found |> Enum.map(& &1.id))
assert event_ids == MapSet.new([event.id, event1.id]) assert event_ids == MapSet.new([event.id, event1.id])
else
err -> err ->
flunk("Failed to get events for an actor #{inspect(err)}") flunk("Failed to get events for an actor #{inspect(err)}")
end end
@ -150,10 +152,10 @@ defmodule Mobilizon.EventsTest do
test "get_public_events_for_actor/3 with limited results", %{actor: actor, event: event} do test "get_public_events_for_actor/3 with limited results", %{actor: actor, event: event} do
event1 = insert(:event, organizer_actor: actor) event1 = insert(:event, organizer_actor: actor)
with {:ok, [%Event{id: event_found_id}], 2} <- case Events.get_public_events_for_actor(actor, 1, 1) do
Events.get_public_events_for_actor(actor, 1, 1) do {:ok, [%Event{id: event_found_id}], 2} ->
assert event_found_id in [event.id, event1.id] assert event_found_id in [event.id, event1.id]
else
err -> err ->
flunk("Failed to get limited events for an actor #{inspect(err)}") flunk("Failed to get limited events for an actor #{inspect(err)}")
end end
@ -345,11 +347,12 @@ defmodule Mobilizon.EventsTest do
valid_attrs = Map.put(@valid_attrs, :event_id, event.id) valid_attrs = Map.put(@valid_attrs, :event_id, event.id)
valid_attrs = Map.put(valid_attrs, :actor_id, actor.id) valid_attrs = Map.put(valid_attrs, :actor_id, actor.id)
with {:ok, %Participant{} = participant} <- Events.create_participant(valid_attrs) do case Events.create_participant(valid_attrs) do
{:ok, %Participant{} = participant} ->
assert participant.event_id == event.id assert participant.event_id == event.id
assert participant.actor_id == actor.id assert participant.actor_id == actor.id
assert participant.role == :creator assert participant.role == :creator
else
err -> err ->
flunk("Failed to create a participant #{inspect(err)}") flunk("Failed to create a participant #{inspect(err)}")
end end
@ -362,10 +365,10 @@ defmodule Mobilizon.EventsTest do
test "update_participant/2 with valid data updates the participant", %{ test "update_participant/2 with valid data updates the participant", %{
participant: participant participant: participant
} do } do
with {:ok, %Participant{} = participant} <- case Events.update_participant(participant, @update_attrs) do
Events.update_participant(participant, @update_attrs) do {:ok, %Participant{} = participant} ->
assert participant.role == :moderator assert participant.role == :moderator
else
err -> err ->
flunk("Failed to update a participant #{inspect(err)}") flunk("Failed to update a participant #{inspect(err)}")
end end
@ -575,10 +578,11 @@ defmodule Mobilizon.EventsTest do
actor = insert(:actor) actor = insert(:actor)
comment_data = Map.merge(@valid_attrs, %{actor_id: actor.id}) comment_data = Map.merge(@valid_attrs, %{actor_id: actor.id})
with {:ok, %Comment{} = comment} <- Events.create_comment(comment_data) do case Events.create_comment(comment_data) do
{:ok, %Comment{} = comment} ->
assert comment.text == "some text" assert comment.text == "some text"
assert comment.actor_id == actor.id assert comment.actor_id == actor.id
else
err -> err ->
flunk("Failed to create a comment #{inspect(err)}") flunk("Failed to create a comment #{inspect(err)}")
end end
@ -591,9 +595,10 @@ defmodule Mobilizon.EventsTest do
test "update_comment/2 with valid data updates the comment" do test "update_comment/2 with valid data updates the comment" do
comment = insert(:comment) comment = insert(:comment)
with {:ok, %Comment{} = comment} <- Events.update_comment(comment, @update_attrs) do case Events.update_comment(comment, @update_attrs) do
{:ok, %Comment{} = comment} ->
assert comment.text == "some updated text" assert comment.text == "some updated text"
else
err -> err ->
flunk("Failed to update a comment #{inspect(err)}") flunk("Failed to update a comment #{inspect(err)}")
end end