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
Mix.shell().info("Tooted") {:ok, _} ->
else Mix.shell().info("Tooted")
{:local_actor, _} -> Mix.shell().error("Failed to toot.\nActor #{from} doesn't exist")
_ -> Mix.shell().error("Failed to toot.") {:local_actor, _} ->
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
{:ok, :public_key.pem_entry_decode(public_key_entry)} [public_key_entry] ->
else {:ok, :public_key.pem_entry_decode(public_key_entry)}
_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,21 +281,21 @@ 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: [ keys: data.keys,
keys: data.keys, name: data.name,
name: data.name, summary: data.summary
summary: data.summary ]
] ],
], 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} ->
else {:ok, actor}
_ -> _ ->
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
actor {:ok, actor} ->
else actor
_ -> _ ->
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, actor} {:ok, _value} ->
else {:ok, actor}
{: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
{:commit, event} %Event{} = event ->
else {:commit, event}
_ -> {: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
{:commit, comment} %Comment{} = comment ->
else {:commit, comment}
_ -> {:ignore, nil}
_ ->
{:ignore, nil}
end end
end) end)
end end

View file

@ -235,8 +235,9 @@ 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 _ <-
|> Repo.update_all([]) do from(u in User, where: u.id == ^user_id, update: [set: [default_actor_id: ^actor_id]])
|> Repo.update_all([]) do
Repo.get!(User, user_id) |> Repo.preload([:default_actor]) Repo.get!(User, user_id) |> Repo.preload([:default_actor])
end end
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
{:ok, %{total: total, elements: elements}} %{:total => total, :elements => [%Actor{}] = elements} ->
else {:ok, %{total: total, elements: elements}}
_ -> _ ->
{: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
{:ok, %{total: total, elements: elements}} {total = total, [%Event{} = elements]} ->
else {:ok, %{total: total, elements: elements}}
_ -> _ ->
{: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
%{total: 1, elements: [actor]} {:ok, actor} ->
else %{total: 1, elements: [actor]}
{: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
%{total: 1, elements: [object]} {:ok, object} ->
else %{total: 1, elements: [object]}
{: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{ [
actor: %Actor{ %Member{
id: member_actor_id actor: %Actor{
} 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
{:ok, %Picture{id: id, file: file} = _pic ->
%{name: file.name, url: file.url, id: id, content_type: file.content_type, size: file.size}} {:ok,
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
Actors.insert_or_update_actor(data, preload) {:ok, data} ->
else Actors.insert_or_update_actor(data, preload)
# 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
{:ok, actor} %Actor{} = actor ->
else {:ok, actor}
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
make_actor_from_url(url) {:ok, %{"url" => url}} when not is_nil(url) ->
else make_actor_from_url(url)
_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
{:halt, actor} {:ok, %Actor{} = actor} ->
else {:halt, actor}
_ -> {: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
{:halt, event} %Event{} = event ->
else {:halt, event}
_ -> {:cont, nil}
_ ->
{:cont, nil}
end end
end), end),

View file

@ -209,19 +209,20 @@ 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, new_actor_data} = ActivityPub.actor_data_from_actor_object(object) {:ok, %Actor{url: url}} ->
{: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)
ActivityPub.update(%{
local: false,
to: data["to"] || [],
cc: data["cc"] || [],
object: object,
actor: url
})
ActivityPub.update(%{
local: false,
to: data["to"] || [],
cc: data["cc"] || [],
object: object,
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
picture {:ok, picture} ->
else picture
_ -> 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
{:commit, res} {:ok, res} ->
else {:commit, res}
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
{:commit, res} {:ok, res} ->
else {:commit, res}
err -> err ->
{:ignore, err} {:ignore, err}
end end
@ -99,21 +101,22 @@ 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
entry = {:ok, html, []} ->
Entry.new(event.url, event.publish_at || event.inserted_at, event.title) entry =
|> Entry.link(event.url, rel: "alternate", type: "text/html") Entry.new(event.url, event.publish_at || event.inserted_at, event.title)
|> Entry.content({:cdata, html}, type: "html") |> Entry.link(event.url, rel: "alternate", type: "text/html")
|> Entry.published(event.publish_at || event.inserted_at) |> Entry.content({:cdata, html}, type: "html")
|> Entry.published(event.publish_at || event.inserted_at)
# Add tags # Add tags
entry = entry =
event.tags event.tags
|> Enum.uniq() |> Enum.uniq()
|> 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
{:commit, res} {:ok, res} ->
else {:commit, res}
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,19 +49,19 @@ 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
if validate_conn(conn, public_key) do {:ok, public_key} ->
true if validate_conn(conn, public_key) do
else true
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"],
{:ok, _actor} <- ActivityPub.make_actor_from_url(actor_id), {:ok, _actor} <- ActivityPub.make_actor_from_url(actor_id),
{:ok, public_key} <- actor_id |> Actor.get_public_key_for_url() do {:ok, public_key} <- actor_id |> Actor.get_public_key_for_url() 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
date {:ok, date} ->
else date
{: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, represent_actor(actor, "JSON")} {:ok, %Actor{} = actor} when not is_nil(actor) ->
else {:ok, represent_actor(actor, "JSON")}
_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
domain [_name, domain] ->
else domain
_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
assert true {:error, %Ecto.Changeset{}} ->
else assert true
_ -> _ ->
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
assert event.begins_on == DateTime.from_naive!(~N[2010-04-17 14:00:00Z], "Etc/UTC") {:ok, %Event{} = event} ->
assert event.description == "some description" assert event.begins_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.description == "some description"
assert event.title == "some title" assert event.ends_on == DateTime.from_naive!(~N[2010-04-17 14:00:00Z], "Etc/UTC")
else assert event.title == "some title"
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
event_ids = MapSet.new(events_found |> Enum.map(& &1.id)) {:ok, events_found, 2} ->
assert event_ids == MapSet.new([event.id, event1.id]) event_ids = MapSet.new(events_found |> Enum.map(& &1.id))
else assert event_ids == MapSet.new([event.id, event1.id])
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
assert participant.event_id == event.id {:ok, %Participant{} = participant} ->
assert participant.actor_id == actor.id assert participant.event_id == event.id
assert participant.role == :creator assert participant.actor_id == actor.id
else assert participant.role == :creator
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
assert comment.text == "some text" {:ok, %Comment{} = comment} ->
assert comment.actor_id == actor.id assert comment.text == "some text"
else assert comment.actor_id == actor.id
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
assert comment.text == "some updated text" {:ok, %Comment{} = comment} ->
else assert comment.text == "some updated text"
err -> err ->
flunk("Failed to update a comment #{inspect(err)}") flunk("Failed to update a comment #{inspect(err)}")
end end