Fix tests

Signed-off-by: Thomas Citharel <tcit@tcit.fr>
This commit is contained in:
Thomas Citharel 2018-11-12 18:17:53 +01:00
parent 0900eb730e
commit a04dfc5293
29 changed files with 645 additions and 508 deletions

View File

@ -3,5 +3,5 @@ defmodule Mobilizon.Activity do
Represents an activity
"""
defstruct [:id, :data, :local, :actor, :recipients, :notifications, :type]
defstruct [:data, :local, :actor, :recipients, :notifications]
end

View File

@ -131,7 +131,6 @@ defmodule Mobilizon.Actors.Actor do
:outbox_url,
:inbox_url,
:type,
:name,
:domain,
:preferred_username,
:keys
@ -179,17 +178,38 @@ defmodule Mobilizon.Actors.Actor do
|> put_change(:local, true)
end
@doc """
Get a public key for a given ActivityPub actor ID (url)
"""
@spec get_public_key_for_url(String.t()) :: {:ok, String.t()}
def get_public_key_for_url(url) do
with {:ok, %Actor{} = actor} <- Actors.get_or_fetch_by_url(url) do
{:ok, actor.keys}
with {:ok, %Actor{keys: keys}} <- Actors.get_or_fetch_by_url(url),
{:ok, public_key} <- prepare_public_key(keys) do
{:ok, public_key}
else
{:error, :pem_decode_error} ->
Logger.error("Error while decoding PEM")
{:error, :pem_decode_error}
_ ->
Logger.error("Unable to fetch actor, so no keys for you")
{:error, :actor_fetch_error}
end
end
@doc """
Convert internal PEM encoded keys to public key format
"""
@spec prepare_public_key(String.t()) :: {:ok, tuple()} | {:error, :pem_decode_error}
def prepare_public_key(public_key_code) do
with [public_key_entry] <- :public_key.pem_decode(public_key_code) do
{:ok, :public_key.pem_entry_decode(public_key_entry)}
else
_err ->
{:error, :pem_decode_error}
end
end
@doc """
Get followers from an actor

View File

@ -6,7 +6,7 @@ defmodule Mobilizon.Actors do
import Ecto.Query, warn: false
alias Mobilizon.Repo
alias Mobilizon.Actors.Actor
alias Mobilizon.Actors.{Actor, Bot, Member, Follower, User}
alias Mobilizon.Actors
alias Mobilizon.Service.ActivityPub
@ -24,10 +24,11 @@ defmodule Mobilizon.Actors do
## Examples
iex> list_actors()
[%Actor{}, ...]
iex> Mobilizon.Actors.list_actors()
[%Mobilizon.Actors.Actor{}]
"""
@spec list_actors() :: list()
def list_actors do
Repo.all(Actor)
end
@ -40,12 +41,13 @@ defmodule Mobilizon.Actors do
## Examples
iex> get_actor!(123)
%Actor{}
%Mobilizon.Actors.Actor{}
iex> get_actor!(456)
** (Ecto.NoResultsError)
"""
@spec get_actor!(integer()) :: Actor.t()
def get_actor!(id) do
Repo.get!(Actor, id)
end
@ -53,7 +55,7 @@ defmodule Mobilizon.Actors do
@doc """
Returns the associated actor for an user, either the default set one or the first found
"""
@spec get_actor_for_user(%Mobilizon.Actors.User{}) :: %Mobilizon.Actors.Actor{}
@spec get_actor_for_user(Mobilizon.Actors.User.t()) :: Mobilizon.Actors.Actor.t()
def get_actor_for_user(%Mobilizon.Actors.User{} = user) do
case user.default_actor_id do
nil -> get_first_actor_for_user(user)
@ -82,10 +84,10 @@ defmodule Mobilizon.Actors do
## Examples
iex> create_actor(%{field: value})
{:ok, %Actor{}}
iex> create_actor(%{preferred_username: "test"})
{:ok, %Mobilizon.Actors.Actor{preferred_username: "test"}}
iex> create_actor(%{field: bad_value})
iex> create_actor(%{preferred_username: nil})
{:error, %Ecto.Changeset{}}
"""
@ -100,10 +102,10 @@ defmodule Mobilizon.Actors do
## Examples
iex> update_actor(actor, %{field: new_value})
{:ok, %Actor{}}
iex> update_actor(%Actor{preferred_username: "toto"}, %{preferred_username: "tata"})
{:ok, %Mobilizon.Actors.Actor{preferred_username: "tata"}}
iex> update_actor(actor, %{field: bad_value})
iex> update_actor(%Actor{preferred_username: "toto"}, %{preferred_username: nil})
{:error, %Ecto.Changeset{}}
"""
@ -118,13 +120,14 @@ defmodule Mobilizon.Actors do
## Examples
iex> delete_actor(actor)
{:ok, %Actor{}}
iex> delete_actor(%Actor{})
{:ok, %Mobilizon.Actors.Actor{}}
iex> delete_actor(actor)
iex> delete_actor(nil)
{:error, %Ecto.Changeset{}}
"""
@spec delete_actor(Actor.t()) :: {:ok, Actor.t()} | {:error, Ecto.Changeset.t()}
def delete_actor(%Actor{} = actor) do
Repo.delete(actor)
end
@ -134,8 +137,8 @@ defmodule Mobilizon.Actors do
## Examples
iex> change_actor(actor)
%Ecto.Changeset{source: %Actor{}}
iex> change_actor(%Actor{})
%Ecto.Changeset{data: %Mobilizon.Actors.Actor{}}
"""
def change_actor(%Actor{} = actor) do
@ -164,10 +167,10 @@ defmodule Mobilizon.Actors do
## Examples
iex> create_group(%{field: value})
{:ok, %Actor{}}
iex> create_group(%{name: "group name"})
{:ok, %Mobilizon.Actors.Actor{}}
iex> create_group(%{field: bad_value})
iex> create_group(%{name: nil})
{:error, %Ecto.Changeset{}}
"""
@ -185,28 +188,20 @@ defmodule Mobilizon.Actors do
## Examples
iex> list_users()
[%User{}, ...]
[%Mobilizon.Actors.User{}]
"""
def list_users do
Repo.all(User)
end
@doc """
List users with their associated actors. No reason for that, so removed
"""
# def list_users_with_actors do
# users = Repo.all(User)
# Repo.preload(users, :actors)
# end
defp blank?(""), do: nil
defp blank?(n), do: n
def insert_or_update_actor(data, preload \\ false) do
cs = Actor.remote_actor_creation(data)
actor =
{:ok, actor} =
Repo.insert(
cs,
on_conflict: [
@ -249,7 +244,7 @@ defmodule Mobilizon.Actors do
## Examples
iex> get_user!(123)
%User{}
%Mobilizon.Actors.User{}
iex> get_user!(456)
** (Ecto.NoResultsError)
@ -257,13 +252,19 @@ defmodule Mobilizon.Actors do
"""
def get_user!(id), do: Repo.get!(User, id)
def get_user_with_actor!(id) do
@doc """
Get an user with it's actors
Raises `Ecto.NoResultsError` if the User does not exist.
"""
@spec get_user_with_actors!(integer()) :: User.t()
def get_user_with_actors!(id) do
user = Repo.get!(User, id)
Repo.preload(user, :actors)
end
@spec get_user_with_actor(integer()) :: %User{}
def get_user_with_actor(id) do
@spec get_user_with_actors(integer()) :: User.t()
def get_user_with_actors(id) do
case Repo.get(User, id) do
nil -> {:error, "User with ID #{id} not found"}
user -> {:ok, Repo.preload(user, :actors)}
@ -271,9 +272,22 @@ defmodule Mobilizon.Actors do
end
@doc """
Get an actor by it's URL (ActivityPub ID)
Get an actor by it's URL (ActivityPub ID). The `:preload` option allows preloading the Followers relation.
Raises `Ecto.NoResultsError` if the Actor does not exist.
## Examples
iex> get_actor_by_url("https://mastodon.server.tld/users/user")
{:ok, %Mobilizon.Actors.Actor{preferred_username: "user"}}
iex> get_actor_by_url("https://mastodon.server.tld/users/user", true)
{:ok, %Mobilizon.Actors.Actor{preferred_username: "user", followers: []}}
iex> get_actor_by_url("non existent")
{:error, :actor_not_found}
"""
@spec get_actor_by_url(String.t(), boolean()) :: {:ok, struct()} | {:error, :actor_not_found}
@spec get_actor_by_url(String.t(), boolean()) :: {:ok, Actor.t()} | {:error, :actor_not_found}
def get_actor_by_url(url, preload \\ false) do
case Repo.get_by(Actor, url: url) do
nil ->
@ -284,6 +298,22 @@ defmodule Mobilizon.Actors do
end
end
@doc """
Get an actor by it's URL (ActivityPub ID). The `:preload` option allows preloading the Followers relation.
Raises `Ecto.NoResultsError` if the Actor does not exist.
## Examples
iex> get_actor_by_url!("https://mastodon.server.tld/users/user")
%Mobilizon.Actors.Actor{}
iex> get_actor_by_url!("https://mastodon.server.tld/users/user", true)
{:ok, %Mobilizon.Actors.Actor{preferred_username: "user", followers: []}}
iex> get_actor_by_url!("non existent")
** (Ecto.NoResultsError)
"""
@spec get_actor_by_url!(String.t(), boolean()) :: struct()
def get_actor_by_url!(url, preload \\ false) do
actor = Repo.get_by!(Actor, url: url)
@ -324,16 +354,32 @@ defmodule Mobilizon.Actors do
end
def get_or_fetch_by_url(url, preload \\ false) do
if {:ok, actor} = get_actor_by_url(url, preload) do
with {:ok, actor} <- get_actor_by_url(url, preload) do
{:ok, actor}
else
case ActivityPub.make_actor_from_url(url, preload) do
{:ok, actor} ->
{:ok, actor}
_ ->
case ActivityPub.make_actor_from_url(url, preload) do
{:ok, actor} ->
{:ok, actor}
_ ->
{:error, "Could not fetch by AP id"}
end
_ ->
{:error, "Could not fetch by AP id"}
end
end
end
def get_or_fetch_by_url!(url, preload \\ false) do
with {:ok, actor} <- get_actor_by_url(url, preload) do
actor
else
_ ->
case ActivityPub.make_actor_from_url(url, preload) do
{:ok, actor} ->
actor
_ ->
raise "Could not fetch by AP id"
end
end
end
@ -503,10 +549,10 @@ defmodule Mobilizon.Actors do
## Examples
iex> create_user(%{field: value})
{:ok, %User{}}
iex> create_user(%{email: "test@test.tld"})
{:ok, %Mobilizon.Actors.User{}}
iex> create_user(%{field: bad_value})
iex> create_user(%{email: "not an email"})
{:error, %Ecto.Changeset{}}
"""
@ -521,11 +567,11 @@ defmodule Mobilizon.Actors do
## Examples
iex> get_user_by_email(user, email)
{:ok, %User{}}
iex> get_user_by_email("test@test.tld", true)
{:ok, %Mobilizon.Actors.User{}}
iex> get_user_by_email(user, wrong_email)
{:error, nil}
iex> get_user_by_email("test@notfound.tld", false)
{:error, :user_not_found}
"""
def get_user_by_email(email, activated \\ nil) do
query =
@ -546,10 +592,10 @@ defmodule Mobilizon.Actors do
## Examples
iex> update_user(user, %{field: new_value})
{:ok, %User{}}
iex> update_user(User{}, %{password: "coucou"})
{:ok, %Mobilizon.Actors.User{}}
iex> update_user(user, %{field: bad_value})
iex> update_user(User{}, %{password: nil})
{:error, %Ecto.Changeset{}}
"""
@ -564,10 +610,10 @@ defmodule Mobilizon.Actors do
## Examples
iex> delete_user(user)
{:ok, %User{}}
iex> delete_user(%User{email: "test@test.tld"})
{:ok, %Mobilizon.Actors.User{}}
iex> delete_user(user)
iex> delete_user(%User{})
{:error, %Ecto.Changeset{}}
"""
@ -580,8 +626,8 @@ defmodule Mobilizon.Actors do
## Examples
iex> change_user(user)
%Ecto.Changeset{source: %User{}}
iex> change_user(%Mobilizon.Actors.User{})
%Ecto.Changeset{data: %Mobilizon.Actors.User{}}
"""
def change_user(%User{} = user) do
@ -598,7 +644,7 @@ defmodule Mobilizon.Actors do
## Examples
iex> get_member!(123)
%Member{}
%Mobilizon.Actors.Member{}
iex> get_member!(456)
** (Ecto.NoResultsError)
@ -611,10 +657,10 @@ defmodule Mobilizon.Actors do
## Examples
iex> create_member(%{field: value})
{:ok, %Member{}}
iex> create_member(%{actor: %Actor{}})
{:ok, %Mobilizon.Actors.Member{}}
iex> create_member(%{field: bad_value})
iex> create_member(%{actor: nil})
{:error, %Ecto.Changeset{}}
"""
@ -632,10 +678,10 @@ defmodule Mobilizon.Actors do
## Examples
iex> update_member(member, %{field: new_value})
{:ok, %Member{}}
iex> update_member(%Member{}, %{role: 3})
{:ok, %Mobilizon.Actors.Member{}}
iex> update_member(member, %{field: bad_value})
iex> update_member(%Member{}, %{role: nil})
{:error, %Ecto.Changeset{}}
"""
@ -650,10 +696,10 @@ defmodule Mobilizon.Actors do
## Examples
iex> delete_member(member)
{:ok, %Member{}}
iex> delete_member(%Member{})
{:ok, %Mobilizon.Actors.Member{}}
iex> delete_member(member)
iex> delete_member(%Member{})
{:error, %Ecto.Changeset{}}
"""
@ -666,8 +712,8 @@ defmodule Mobilizon.Actors do
## Examples
iex> change_member(member)
%Ecto.Changeset{source: %Member{}}
iex> change_member(%Member{})
%Ecto.Changeset{data: %Mobilizon.Actors.Member{}}
"""
def change_member(%Member{} = member) do
@ -702,7 +748,7 @@ defmodule Mobilizon.Actors do
## Examples
iex> list_bots()
[%Bot{}, ...]
[%Mobilizon.Actors.Bot{}]
"""
def list_bots do
@ -717,7 +763,7 @@ defmodule Mobilizon.Actors do
## Examples
iex> get_bot!(123)
%Bot{}
%Mobilizon.Actors.Bot{}
iex> get_bot!(456)
** (Ecto.NoResultsError)
@ -735,10 +781,10 @@ defmodule Mobilizon.Actors do
## Examples
iex> create_bot(%{field: value})
{:ok, %Bot{}}
iex> create_bot(%{source: "toto"})
{:ok, %Mobilizon.Actors.Bot{}}
iex> create_bot(%{field: bad_value})
iex> create_bot(%{source: nil})
{:error, %Ecto.Changeset{}}
"""
@ -753,10 +799,10 @@ defmodule Mobilizon.Actors do
## Examples
iex> update_bot(bot, %{field: new_value})
{:ok, %Bot{}}
iex> update_bot(%Bot{}, %{source: "new"})
{:ok, %Mobilizon.Actors.Bot{}}
iex> update_bot(bot, %{field: bad_value})
iex> update_bot(%Bot{}, %{source: nil})
{:error, %Ecto.Changeset{}}
"""
@ -771,10 +817,10 @@ defmodule Mobilizon.Actors do
## Examples
iex> delete_bot(bot)
{:ok, %Bot{}}
iex> delete_bot(%Bot{})
{:ok, %Mobilizon.Actors.Bot{}}
iex> delete_bot(bot)
iex> delete_bot(%Bot{})
{:error, %Ecto.Changeset{}}
"""
@ -787,8 +833,8 @@ defmodule Mobilizon.Actors do
## Examples
iex> change_bot(bot)
%Ecto.Changeset{source: %Bot{}}
iex> change_bot(%Bot{})
%Ecto.Changeset{data: %Mobilizon.Actors.Bot{}}
"""
def change_bot(%Bot{} = bot) do
@ -805,7 +851,7 @@ defmodule Mobilizon.Actors do
## Examples
iex> get_follower!(123)
%Follower{}
%Mobilizon.Actors.Follower{}
iex> get_follower!(456)
** (Ecto.NoResultsError)
@ -821,10 +867,10 @@ defmodule Mobilizon.Actors do
## Examples
iex> create_follower(%{field: value})
{:ok, %Follower{}}
iex> create_follower(%{actor: %Actor{}})
{:ok, %Mobilizon.Actors.Follower{}}
iex> create_follower(%{field: bad_value})
iex> create_follower(%{actor: nil})
{:error, %Ecto.Changeset{}}
"""
@ -839,10 +885,10 @@ defmodule Mobilizon.Actors do
## Examples
iex> update_follower(follower, %{field: new_value})
{:ok, %Follower{}}
iex> update_follower(Follower{}, %{approved: true})
{:ok, %Mobilizon.Actors.Follower{}}
iex> update_follower(follower, %{field: bad_value})
iex> update_follower(Follower{}, %{approved: nil})
{:error, %Ecto.Changeset{}}
"""
@ -857,10 +903,10 @@ defmodule Mobilizon.Actors do
## Examples
iex> delete_follower(follower)
{:ok, %Follower{}}
iex> delete_follower(Follower{})
{:ok, %Mobilizon.Actors.Follower{}}
iex> delete_follower(follower)
iex> delete_follower(Follower{})
{:error, %Ecto.Changeset{}}
"""
@ -873,8 +919,8 @@ defmodule Mobilizon.Actors do
## Examples
iex> change_follower(follower)
%Ecto.Changeset{source: %Follower{}}
iex> change_follower(Follower{})
%Ecto.Changeset{data: %Mobilizon.Actors.Follower{}}
"""
def change_follower(%Follower{} = follower) do

View File

@ -1,7 +1,7 @@
defmodule Mobilizon.Actors.Service.Tools do
alias Mobilizon.Actors.User
@spec we_can_send_email(User.t()) :: boolean
@spec we_can_send_email(User.t(), atom()) :: :ok | {:error, :email_too_soon}
def we_can_send_email(%User{} = user, key \\ :reset_password_sent_at) do
case Map.get(user, key) do
nil ->

View File

@ -142,7 +142,7 @@ defmodule Mobilizon.Events do
Gets an event by it's URL
"""
def get_event_full_by_url!(url) do
event = Repo.get_by(Event, url: url)
event = Repo.get_by!(Event, url: url)
Repo.preload(event, [
:organizer_actor,
@ -326,7 +326,7 @@ defmodule Mobilizon.Events do
"""
def get_category!(id), do: Repo.get!(Category, id)
@spec get_category_by_title(String.t()) :: tuple()
@spec get_category_by_title(String.t()) :: Category.t() | nil
def get_category_by_title(title) when is_binary(title) do
Repo.get_by(Category, title: title)
end

View File

@ -4,6 +4,7 @@ defmodule MobilizonWeb.ActivityPubController do
alias Mobilizon.Events.{Event, Comment}
alias MobilizonWeb.ActivityPub.{ObjectView, ActorView}
alias Mobilizon.Service.ActivityPub
alias Mobilizon.Service.ActivityPub.Utils
alias Mobilizon.Service.Federator
require Logger
@ -46,7 +47,7 @@ defmodule MobilizonWeb.ActivityPubController do
true <- event.public do
conn
|> put_resp_header("content-type", "application/activity+json")
|> json(ObjectView.render("event.json", %{event: event}))
|> json(ObjectView.render("event.json", %{event: event |> Utils.make_event_data()}))
else
_ ->
{:error, :not_found}
@ -60,7 +61,7 @@ defmodule MobilizonWeb.ActivityPubController do
# true <- comment.public do
conn
|> put_resp_header("content-type", "application/activity+json")
|> json(ObjectView.render("comment.json", %{comment: comment}))
|> json(ObjectView.render("comment.json", %{comment: comment |> Utils.make_comment_data()}))
else
_ ->
{:error, :not_found}
@ -137,11 +138,11 @@ defmodule MobilizonWeb.ActivityPubController do
headers = Enum.into(conn.req_headers, %{})
if String.contains?(headers["signature"], params["actor"]) do
Logger.info(
Logger.error(
"Signature validation error for: #{params["actor"]}, make sure you are forwarding the HTTP Host header!"
)
Logger.info(inspect(conn.req_headers))
Logger.error(inspect(conn.req_headers))
end
json(conn, "error")

View File

@ -24,7 +24,7 @@ defmodule MobilizonWeb.Guardian do
try do
case Integer.parse(uid_str) do
{uid, ""} ->
{:ok, Actors.get_user_with_actor!(uid)}
{:ok, Actors.get_user_with_actors!(uid)}
_ ->
{:error, :invalid_id}

View File

@ -18,34 +18,31 @@ defmodule MobilizonWeb.HTTPSignaturePlug do
end
def call(conn, _opts) do
user = conn.params["actor"]
actor = conn.params["actor"]
Logger.debug(fn ->
"Checking sig for #{user}"
"Checking sig for #{actor}"
end)
with [signature | _] <- get_req_header(conn, "signature") do
cond do
signature && String.contains?(signature, user) ->
conn =
conn
|> put_req_header(
"(request-target)",
String.downcase("#{conn.method}") <> " #{conn.request_path}"
)
[signature | _] = get_req_header(conn, "signature")
assign(conn, :valid_signature, HTTPSignatures.validate_conn(conn))
signature ->
Logger.debug("Signature not from actor")
assign(conn, :valid_signature, false)
true ->
Logger.debug("No signature header!")
cond do
# Dialyzer doesn't like this line
signature && String.contains?(signature, actor) ->
conn =
conn
end
else
_ ->
|> put_req_header(
"(request-target)",
String.downcase("#{conn.method}") <> " #{conn.request_path}"
)
assign(conn, :valid_signature, HTTPSignatures.validate_conn(conn))
signature ->
Logger.debug("Signature not from actor")
assign(conn, :valid_signature, false)
true ->
Logger.debug("No signature header!")
conn
end

View File

@ -6,7 +6,7 @@ defmodule MobilizonWeb.Resolvers.User do
Find an user by it's ID
"""
def find_user(_parent, %{id: id}, _resolution) do
Actors.get_user_with_actor(id)
Actors.get_user_with_actors(id)
end
@doc """

View File

@ -13,11 +13,15 @@ defmodule MobilizonWeb.Router do
plug(:accepts, ["json", "jrd-json"])
end
pipeline :activity_pub do
pipeline :activity_pub_signature do
plug(:accepts, ["activity-json", "html"])
plug(MobilizonWeb.HTTPSignaturePlug)
end
pipeline :activity_pub do
plug(:accepts, ["activity-json", "html"])
end
pipeline :browser do
plug(:accepts, ["html"])
plug(:fetch_session)
@ -56,6 +60,10 @@ defmodule MobilizonWeb.Router do
get("/@:name/followers", ActivityPubController, :followers)
get("/events/:uuid", ActivityPubController, :event)
get("/comments/:uuid", ActivityPubController, :comment)
end
scope "/", MobilizonWeb do
pipe_through(:activity_pub_signature)
post("/@:name/inbox", ActivityPubController, :inbox)
post("/inbox", ActivityPubController, :inbox)
end

View File

@ -309,10 +309,10 @@ defmodule MobilizonWeb.Schema do
resolve(&Resolvers.User.change_default_actor/3)
end
@desc "Upload a picture"
field :upload_picture, :picture do
arg(:file, non_null(:upload))
resolve(&Resolvers.Upload.upload_picture/3)
end
# @desc "Upload a picture"
# field :upload_picture, :picture do
# arg(:file, non_null(:upload))
# resolve(&Resolvers.Upload.upload_picture/3)
# end
end
end

View File

@ -97,11 +97,11 @@ defmodule MobilizonWeb.ActivityPub.ActorView do
{activities, total} = ActivityPub.fetch_public_activities_for_actor(actor, page)
collection =
Enum.map(activities, fn act ->
{:ok, data} = Transmogrifier.prepare_outgoing(act.data)
data
end)
# collection =
# Enum.map(activities, fn act ->
# {:ok, data} = Transmogrifier.prepare_outgoing(act.data)
# data
# end)
iri = "#{actor.url}/outbox"
@ -127,9 +127,9 @@ defmodule MobilizonWeb.ActivityPub.ActorView do
end
end
def render("activity.json", %{activity: %Activity{local: local} = activity}) do
def render("activity.json", %{activity: %Activity{local: local, data: data} = activity}) do
%{
"id" => activity.data.url <> "/activity",
"id" => data["id"],
"type" =>
if local do
"Create"
@ -139,14 +139,14 @@ defmodule MobilizonWeb.ActivityPub.ActorView do
"actor" => activity.actor,
# Not sure if needed since this is used into outbox
"published" => Timex.now(),
"to" => ["https://www.w3.org/ns/activitystreams#Public"],
"to" => activity.recipients,
"object" =>
case activity.type do
:Event ->
render_one(activity.data, ObjectView, "event.json", as: :event)
case data["type"] do
"Event" ->
render_one(data, ObjectView, "event.json", as: :event)
:Comment ->
render_one(activity.data, ObjectView, "comment.json", as: :comment)
"Note" ->
render_one(data, ObjectView, "comment.json", as: :comment)
end
}
|> Map.merge(Utils.make_json_ld_header())

View File

@ -7,13 +7,14 @@ defmodule MobilizonWeb.ActivityPub.ObjectView do
def render("event.json", %{event: event}) do
event = %{
"type" => "Event",
"id" => event.url,
"name" => event.title,
"category" => render_one(event.category, ObjectView, "category.json", as: :category),
"content" => event.description,
"mediaType" => "text/html",
"published" => Timex.format!(event.inserted_at, "{ISO:Extended}"),
"updated" => Timex.format!(event.updated_at, "{ISO:Extended}")
"actor" => event["actor"],
"id" => event["id"],
"name" => event["title"],
"category" => render_one(event["category"], ObjectView, "category.json", as: :category),
"content" => event["summary"],
"mediaType" => "text/html"
# "published" => Timex.format!(event.inserted_at, "{ISO:Extended}"),
# "updated" => Timex.format!(event.updated_at, "{ISO:Extended}")
}
Map.merge(event, Utils.make_json_ld_header())
@ -21,16 +22,16 @@ defmodule MobilizonWeb.ActivityPub.ObjectView do
def render("comment.json", %{comment: comment}) do
comment = %{
"actor" => comment.actor.url,
"uuid" => comment.uuid,
"actor" => comment["actor"],
"uuid" => comment["uuid"],
# The activity should have attributedTo, not the comment itself
# "attributedTo" => comment.attributed_to,
"type" => "Note",
"id" => comment.url,
"content" => comment.text,
"mediaType" => "text/html",
"published" => Timex.format!(comment.inserted_at, "{ISO:Extended}"),
"updated" => Timex.format!(comment.updated_at, "{ISO:Extended}")
"id" => comment["id"],
"content" => comment["content"],
"mediaType" => "text/html"
# "published" => Timex.format!(comment.inserted_at, "{ISO:Extended}"),
# "updated" => Timex.format!(comment.updated_at, "{ISO:Extended}")
}
Map.merge(comment, Utils.make_json_ld_header())

View File

@ -19,14 +19,21 @@ defmodule Mobilizon.Service.ActivityPub do
require Logger
import Mobilizon.Service.ActivityPub.Utils
@doc """
Get recipients for an activity or object
"""
@spec get_recipients(map()) :: list()
def get_recipients(data) do
(data["to"] || []) ++ (data["cc"] || [])
end
def insert(map, local \\ true) when is_map(map) do
Logger.debug("preparing an activity")
Logger.debug(inspect(map))
@doc """
Wraps an object into an activity
TODO: Rename me
"""
@spec insert(map(), boolean()) :: {:ok, %Activity{}} | {:error, any()}
def insert(map, local \\ true) when is_map(map) do
with map <- lazy_put_activity_defaults(map),
:ok <- insert_full_object(map, local) do
object_id =
@ -56,10 +63,10 @@ defmodule Mobilizon.Service.ActivityPub do
end
end
def fetch_object_from_url(url, :event), do: fetch_event_from_url(url)
def fetch_object_from_url(url, :note), do: fetch_note_from_url(url)
@spec fetch_object_from_url(String.t()) :: tuple()
@doc """
Fetch an object from an URL, from our local database of events and comments, then eventually remote
"""
@spec fetch_object_from_url(String.t()) :: {:ok, %Event{}} | {:ok, %Comment{}} | {:error, any()}
def fetch_object_from_url(url) do
with true <- String.starts_with?(url, "http"),
nil <- Events.get_event_by_url(url),
@ -95,29 +102,6 @@ defmodule Mobilizon.Service.ActivityPub do
end
end
@spec fetch_object_from_url(String.t()) :: tuple()
def fetch_event_from_url(url) do
with nil <- Events.get_event_by_url(url) do
Logger.info("Fetching #{url} via AP")
fetch_object_from_url(url)
else
%Event{} = comment ->
{:ok, comment}
end
end
@spec fetch_object_from_url(String.t()) :: tuple()
def fetch_note_from_url(url) do
with nil <- Events.get_comment_from_url(url) do
Logger.info("Fetching #{url} via AP")
fetch_object_from_url(url)
else
%Comment{} = comment ->
{:ok, comment}
end
end
def create(%{to: to, actor: actor, object: object} = params) do
Logger.debug("creating an activity")
additional = params[:additional] || %{}
@ -136,8 +120,8 @@ defmodule Mobilizon.Service.ActivityPub do
{:ok, activity}
else
err ->
Logger.debug("Something went wrong")
Logger.debug(inspect(err))
Logger.error("Something went wrong")
Logger.error(inspect(err))
end
end
@ -216,6 +200,10 @@ defmodule Mobilizon.Service.ActivityPub do
def create_public_activities(%Actor{} = actor) do
end
@doc """
Create an actor locally by it's URL (AP ID)
"""
@spec make_actor_from_url(String.t(), boolean()) :: {:ok, %Actor{}} | {:error, any()}
def make_actor_from_url(url, preload \\ false) do
with {:ok, data} <- fetch_and_prepare_actor_from_url(url) do
Actors.insert_or_update_actor(data, preload)
@ -231,6 +219,9 @@ defmodule Mobilizon.Service.ActivityPub do
end
end
@doc """
Find an actor in our local database or call Webfinger to find what's its AP ID is and then fetch it
"""
@spec find_or_make_actor_from_nickname(String.t()) :: tuple()
def find_or_make_actor_from_nickname(nickname) do
with %Actor{} = actor <- Actors.get_actor_by_name(nickname) do
@ -240,6 +231,10 @@ defmodule Mobilizon.Service.ActivityPub do
end
end
@doc """
Create an actor inside our database from username, using Webfinger to find out it's AP ID and then fetch it
"""
@spec make_actor_from_nickname(String.t()) :: {:ok, %Actor{}} | {:error, any()}
def make_actor_from_nickname(nickname) do
with {:ok, %{"url" => url}} when not is_nil(url) <- WebFinger.finger(nickname) do
make_actor_from_url(url)
@ -288,12 +283,6 @@ defmodule Mobilizon.Service.ActivityPub do
"content-length": byte_size(json)
})
Logger.debug("signature")
Logger.debug(inspect(signature))
Logger.debug("body json")
Logger.debug(inspect(json))
{:ok, response} =
HTTPoison.post(
inbox,
@ -301,19 +290,21 @@ defmodule Mobilizon.Service.ActivityPub do
[{"Content-Type", "application/activity+json"}, {"signature", signature}],
hackney: [pool: :default]
)
Logger.debug(inspect(response))
end
def fetch_and_prepare_actor_from_url(url) do
@doc """
Fetching a remote actor's informations through it's AP ID
"""
@spec fetch_and_prepare_actor_from_url(String.t()) :: {:ok, struct()} | {:error, atom()} | any()
defp fetch_and_prepare_actor_from_url(url) do
Logger.debug("Fetching and preparing actor from url")
with {:ok, %HTTPoison.Response{status_code: 200, body: body}} <-
HTTPoison.get(url, [Accept: "application/activity+json"], follow_redirect: true),
{:ok, data} <- Jason.decode(body) do
user_data_from_user_object(data)
actor_data_from_actor_object(data)
else
# User is gone, probably deleted
# Actor is gone, probably deleted
{:ok, %HTTPoison.Response{status_code: 410}} ->
{:error, :actor_deleted}
@ -323,8 +314,12 @@ defmodule Mobilizon.Service.ActivityPub do
end
end
def user_data_from_user_object(data) do
user_data = %{
@doc """
Creating proper actor data struct from AP data
"""
@spec actor_data_from_actor_object(map()) :: {:ok, map()}
def actor_data_from_actor_object(data) when is_map(data) do
actor_data = %{
url: data["id"],
info: %{
"ap_enabled" => true,
@ -347,30 +342,22 @@ defmodule Mobilizon.Service.ActivityPub do
type: data["type"]
}
Logger.debug("user_data_from_user_object")
Logger.debug(inspect(user_data))
{:ok, user_data}
{:ok, actor_data}
end
@spec fetch_public_activities_for_actor(Actor.t(), integer(), integer()) :: list()
@doc """
Return all public activities (events & comments) for an actor
"""
@spec fetch_public_activities_for_actor(Actor.t(), integer(), integer()) :: {list(), integer()}
def fetch_public_activities_for_actor(%Actor{} = actor, page \\ 1, limit \\ 10) do
case actor.type do
:Person ->
{:ok, events, total} = Events.get_events_for_actor(actor, page, limit)
{:ok, comments, total} = Events.get_comments_for_actor(actor, page, limit)
event_activities =
Enum.map(events, fn event ->
{:ok, activity} = event_to_activity(event)
activity
end)
event_activities = Enum.map(events, &event_to_activity/1)
comment_activities =
Enum.map(comments, fn comment ->
{:ok, activity} = comment_to_activity(comment)
activity
end)
comment_activities = Enum.map(comments, &comment_to_activity/1)
activities = event_activities ++ comment_activities
@ -402,37 +389,36 @@ defmodule Mobilizon.Service.ActivityPub do
end
end
@doc """
Create an activity from an event
"""
@spec event_to_activity(%Event{}, boolean()) :: Activity.t()
defp event_to_activity(%Event{} = event, local \\ true) do
activity = %Activity{
type: :Event,
data: event,
local: local,
%Activity{
recipients: ["https://www.w3.org/ns/activitystreams#Public"],
actor: event.organizer_actor.url,
recipients: ["https://www.w3.org/ns/activitystreams#Public"]
data: event |> make_event_data,
local: local
}
# Notification.create_notifications(activity)
# stream_out(activity)
{:ok, activity}
end
@doc """
Create an activity from a comment
"""
@spec comment_to_activity(%Comment{}, boolean()) :: Activity.t()
defp comment_to_activity(%Comment{} = comment, local \\ true) do
activity = %Activity{
type: :Comment,
data: comment,
local: local,
%Activity{
recipients: ["https://www.w3.org/ns/activitystreams#Public"],
actor: comment.actor.url,
recipients: ["https://www.w3.org/ns/activitystreams#Public"]
data: comment |> make_comment_data,
local: local
}
# Notification.create_notifications(activity)
# stream_out(activity)
{:ok, activity}
end
defp ical_event_to_activity(%ExIcal.Event{} = ical_event, %Actor{} = actor, source) do
# Logger.debug(inspect ical_event)
# TODO : refactor me !
# TODO : also, there should be a form of cache that allows this to be more efficient
category =
if is_nil(ical_event.categories) do
nil

View File

@ -26,13 +26,16 @@ defmodule Mobilizon.Service.ActivityPub.Transmogrifier do
when not is_nil(in_reply_to) do
in_reply_to_id =
cond do
is_bitstring(in_reply_to) -> # If the inReplyTo is just an AP ID
# If the inReplyTo is just an AP ID
is_bitstring(in_reply_to) ->
in_reply_to
is_map(in_reply_to) && is_bitstring(in_reply_to["id"]) -> # If the inReplyTo is a object itself
# If the inReplyTo is a object itself
is_map(in_reply_to) && is_bitstring(in_reply_to["id"]) ->
in_reply_to["id"]
is_list(in_reply_to) && is_bitstring(Enum.at(in_reply_to, 0)) -> # If the inReplyTo is an array
# If the inReplyTo is an array
is_list(in_reply_to) && is_bitstring(Enum.at(in_reply_to, 0)) ->
Enum.at(in_reply_to, 0)
true ->
@ -44,7 +47,7 @@ defmodule Mobilizon.Service.ActivityPub.Transmogrifier do
case fetch_obj_helper(in_reply_to_id) do
{:ok, replied_object} ->
object
|> Map.put("inReplyTo", replied_object.data["id"])
|> Map.put("inReplyTo", replied_object.url)
e ->
Logger.error("Couldn't fetch #{in_reply_to_id} #{inspect(e)}")
@ -128,7 +131,7 @@ defmodule Mobilizon.Service.ActivityPub.Transmogrifier do
# ) do
# with %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
# {:ok, object} <-
# get_obj_helper(object_id) || ActivityPub.fetch_object_from_id(object_id),
# fetch_obj_helper(object_id) || ActivityPub.fetch_object_from_id(object_id),
# {:ok, activity, object} <- ActivityPub.like(actor, object, id, false) do
# {:ok, activity}
# else
@ -136,18 +139,18 @@ defmodule Mobilizon.Service.ActivityPub.Transmogrifier do
# end
# end
#
def handle_incoming(
%{"type" => "Announce", "object" => object_id, "actor" => actor, "id" => id} = data
) do
with {:ok, %Actor{} = actor} <- Actors.get_or_fetch_by_url(actor),
{:ok, object} <-
get_obj_helper(object_id) || ActivityPub.fetch_event_from_url(object_id),
{:ok, activity, object} <- ActivityPub.announce(actor, object, id, false) do
{:ok, activity}
else
_e -> :error
end
end
# def handle_incoming(
# %{"type" => "Announce", "object" => object_id, "actor" => actor, "id" => id} = data
# ) do
# with {:ok, %Actor{} = actor} <- Actors.get_or_fetch_by_url(actor),
# {:ok, object} <-
# fetch_obj_helper(object_id) || ActivityPub.fetch_object_from_url(object_id),
# {:ok, activity, object} <- ActivityPub.announce(actor, object, id, false) do
# {:ok, activity}
# else
# _e -> :error
# end
# end
#
# def handle_incoming(
@ -155,7 +158,7 @@ defmodule Mobilizon.Service.ActivityPub.Transmogrifier do
# data
# ) do
# with %User{ap_id: ^actor_id} = actor <- User.get_by_ap_id(object["id"]) do
# {:ok, new_user_data} = ActivityPub.user_data_from_user_object(object)
# {:ok, new_user_data} = ActivityPub.actor_data_from_actor_object(object)
#
# banner = new_user_data[:info]["banner"]
#
@ -194,7 +197,7 @@ defmodule Mobilizon.Service.ActivityPub.Transmogrifier do
#
# with %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
# {:ok, object} <-
# get_obj_helper(object_id) || ActivityPub.fetch_object_from_id(object_id),
# fetch_obj_helper(object_id) || ActivityPub.fetch_object_from_id(object_id),
# {:ok, activity} <- ActivityPub.delete(object, false) do
# {:ok, activity}
# else
@ -208,13 +211,9 @@ defmodule Mobilizon.Service.ActivityPub.Transmogrifier do
#
def handle_incoming(_), do: :error
def get_obj_helper(id) do
if object = Object.get_by_ap_id(id), do: {:ok, object}, else: nil
end
def set_reply_to_uri(%{"inReplyTo" => in_reply_to} = object) do