Page MenuHomePhorge

No OneTemporary

Size
75 KB
Referenced Files
None
Subscribers
None
diff --git a/lib/pleroma/activity.ex b/lib/pleroma/activity.ex
index 8559ae6a9..079823312 100644
--- a/lib/pleroma/activity.ex
+++ b/lib/pleroma/activity.ex
@@ -1,370 +1,383 @@
# Pleroma: A lightweight social networking server
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Activity do
use Ecto.Schema
alias Pleroma.Activity
alias Pleroma.Activity.Queries
alias Pleroma.Bookmark
alias Pleroma.Notification
alias Pleroma.Object
alias Pleroma.Repo
alias Pleroma.ReportNote
alias Pleroma.ThreadMute
alias Pleroma.User
alias Pleroma.Web.ActivityPub.ActivityPub
import Ecto.Changeset
import Ecto.Query
@type t :: %__MODULE__{}
@type actor :: String.t()
@primary_key {:id, FlakeId.Ecto.CompatType, autogenerate: true}
schema "activities" do
field(:data, :map)
field(:local, :boolean, default: true)
field(:actor, :string)
field(:recipients, {:array, :string}, default: [])
field(:thread_muted?, :boolean, virtual: true)
# A field that can be used if you need to join some kind of other
# id to order / paginate this field by
field(:pagination_id, :string, virtual: true)
# This is a fake relation,
# do not use outside of with_preloaded_user_actor/with_joined_user_actor
has_one(:user_actor, User, on_delete: :nothing, foreign_key: :id)
# This is a fake relation, do not use outside of with_preloaded_bookmark/get_bookmark
has_one(:bookmark, Bookmark)
# This is a fake relation, do not use outside of with_preloaded_report_notes
has_many(:report_notes, ReportNote)
has_many(:notifications, Notification, on_delete: :delete_all)
# Attention: this is a fake relation, don't try to preload it blindly and expect it to work!
# The foreign key is embedded in a jsonb field.
#
# To use it, you probably want to do an inner join and a preload:
#
# ```
# |> join(:inner, [activity], o in Object,
# on: fragment("(?->>'id') = COALESCE((?)->'object'->> 'id', (?)->>'object')",
# o.data, activity.data, activity.data))
# |> preload([activity, object], [object: object])
# ```
#
# As a convenience, Activity.with_preloaded_object() sets up an inner join and preload for the
# typical case.
has_one(:object, Object, on_delete: :nothing, foreign_key: :id)
timestamps()
end
def with_joined_object(query, join_type \\ :inner) do
join(query, join_type, [activity], o in Object,
on:
fragment(
"(?->>'id') = COALESCE(?->'object'->>'id', ?->>'object')",
o.data,
activity.data,
activity.data
),
as: :object
)
end
def with_preloaded_object(query, join_type \\ :inner) do
query
|> has_named_binding?(:object)
|> if(do: query, else: with_joined_object(query, join_type))
|> preload([activity, object: object], object: object)
end
# Note: applies to fake activities (ActivityPub.Utils.get_notified_from_object/1 etc.)
def user_actor(%Activity{actor: nil}), do: nil
def user_actor(%Activity{} = activity) do
with %User{} <- activity.user_actor do
activity.user_actor
else
_ -> User.get_cached_by_ap_id(activity.actor)
end
end
def with_joined_user_actor(query, join_type \\ :inner) do
join(query, join_type, [activity], u in User,
on: u.ap_id == activity.actor,
as: :user_actor
)
end
def with_preloaded_user_actor(query, join_type \\ :inner) do
query
|> with_joined_user_actor(join_type)
|> preload([activity, user_actor: user_actor], user_actor: user_actor)
end
def with_preloaded_bookmark(query, %User{} = user) do
from([a] in query,
left_join: b in Bookmark,
on: b.user_id == ^user.id and b.activity_id == a.id,
preload: [bookmark: b]
)
end
def with_preloaded_bookmark(query, _), do: query
def with_preloaded_report_notes(query) do
from([a] in query,
left_join: r in ReportNote,
on: a.id == r.activity_id,
preload: [report_notes: r]
)
end
def with_preloaded_report_notes(query, _), do: query
def with_set_thread_muted_field(query, %User{} = user) do
from([a] in query,
left_join: tm in ThreadMute,
on: tm.user_id == ^user.id and tm.context == fragment("?->>'context'", a.data),
as: :thread_mute,
select: %Activity{a | thread_muted?: not is_nil(tm.id)}
)
end
def with_set_thread_muted_field(query, _), do: query
def get_by_ap_id(ap_id) do
ap_id
|> Queries.by_ap_id()
|> Repo.one()
end
def get_bookmark(%Activity{} = activity, %User{} = user) do
if Ecto.assoc_loaded?(activity.bookmark) do
activity.bookmark
else
Bookmark.get(user.id, activity.id)
end
end
def get_bookmark(_, _), do: nil
def get_report(activity_id) do
opts = %{
type: "Flag",
skip_preload: true,
preload_report_notes: true
}
ActivityPub.fetch_activities_query([], opts)
|> where(id: ^activity_id)
|> Repo.one()
end
def change(struct, params \\ %{}) do
struct
|> cast(params, [:data, :recipients])
|> validate_required([:data])
|> unique_constraint(:ap_id, name: :activities_unique_apid_index)
end
def get_by_ap_id_with_object(ap_id) do
ap_id
|> Queries.by_ap_id()
|> with_preloaded_object(:left)
|> Repo.one()
end
@spec get_by_id(String.t()) :: Activity.t() | nil
def get_by_id(id) do
case FlakeId.flake_id?(id) do
true ->
Activity
|> where([a], a.id == ^id)
|> restrict_deactivated_users()
|> Repo.one()
_ ->
nil
end
end
+ def get_by_id_with_user_actor(id) do
+ case FlakeId.flake_id?(id) do
+ true ->
+ Activity
+ |> where([a], a.id == ^id)
+ |> with_preloaded_user_actor()
+ |> Repo.one()
+
+ _ ->
+ nil
+ end
+ end
+
def get_by_id_with_object(id) do
Activity
|> where(id: ^id)
|> with_preloaded_object()
|> Repo.one()
end
def all_by_ids_with_object(ids) do
Activity
|> where([a], a.id in ^ids)
|> with_preloaded_object()
|> Repo.all()
end
@doc """
Accepts `ap_id` or list of `ap_id`.
Returns a query.
"""
@spec create_by_object_ap_id(String.t() | [String.t()]) :: Ecto.Queryable.t()
def create_by_object_ap_id(ap_id) do
ap_id
|> Queries.by_object_id()
|> Queries.by_type("Create")
end
def get_all_create_by_object_ap_id(ap_id) do
ap_id
|> create_by_object_ap_id()
|> Repo.all()
end
def get_create_by_object_ap_id(ap_id) when is_binary(ap_id) do
create_by_object_ap_id(ap_id)
|> restrict_deactivated_users()
|> Repo.one()
end
def get_create_by_object_ap_id(_), do: nil
@doc """
Accepts `ap_id` or list of `ap_id`.
Returns a query.
"""
@spec create_by_object_ap_id_with_object(String.t() | [String.t()]) :: Ecto.Queryable.t()
def create_by_object_ap_id_with_object(ap_id) do
ap_id
|> create_by_object_ap_id()
|> with_preloaded_object()
end
def get_create_by_object_ap_id_with_object(ap_id) when is_binary(ap_id) do
ap_id
|> create_by_object_ap_id_with_object()
|> Repo.one()
end
def get_create_by_object_ap_id_with_object(_), do: nil
defp get_in_reply_to_activity_from_object(%Object{data: %{"inReplyTo" => ap_id}}) do
get_create_by_object_ap_id_with_object(ap_id)
end
defp get_in_reply_to_activity_from_object(_), do: nil
def get_in_reply_to_activity(%Activity{} = activity) do
get_in_reply_to_activity_from_object(Object.normalize(activity))
end
def normalize(obj) when is_map(obj), do: get_by_ap_id_with_object(obj["id"])
def normalize(ap_id) when is_binary(ap_id), do: get_by_ap_id_with_object(ap_id)
def normalize(_), do: nil
def delete_all_by_object_ap_id(id) when is_binary(id) do
id
|> Queries.by_object_id()
|> Queries.exclude_type("Delete")
|> select([u], u)
|> Repo.delete_all()
|> elem(1)
|> Enum.find(fn
%{data: %{"type" => "Create", "object" => ap_id}} when is_binary(ap_id) -> ap_id == id
%{data: %{"type" => "Create", "object" => %{"id" => ap_id}}} -> ap_id == id
_ -> nil
end)
|> purge_web_resp_cache()
end
def delete_all_by_object_ap_id(_), do: nil
defp purge_web_resp_cache(%Activity{} = activity) do
%{path: path} = URI.parse(activity.data["id"])
Cachex.del(:web_resp_cache, path)
activity
end
defp purge_web_resp_cache(nil), do: nil
def follow_accepted?(
%Activity{data: %{"type" => "Follow", "object" => followed_ap_id}} = activity
) do
with %User{} = follower <- Activity.user_actor(activity),
%User{} = followed <- User.get_cached_by_ap_id(followed_ap_id) do
Pleroma.FollowingRelationship.following?(follower, followed)
else
_ -> false
end
end
def follow_accepted?(_), do: false
def all_by_actor_and_id(actor, status_ids \\ [])
def all_by_actor_and_id(_actor, []), do: []
def all_by_actor_and_id(actor, status_ids) do
Activity
|> where([s], s.id in ^status_ids)
|> where([s], s.actor == ^actor)
|> Repo.all()
end
def follow_requests_for_actor(%User{ap_id: ap_id}) do
ap_id
|> Queries.by_object_id()
|> Queries.by_type("Follow")
|> where([a], fragment("? ->> 'state' = 'pending'", a.data))
end
def following_requests_for_actor(%User{ap_id: ap_id}) do
Queries.by_type("Follow")
|> where([a], fragment("?->>'state' = 'pending'", a.data))
|> where([a], a.actor == ^ap_id)
|> Repo.all()
end
def restrict_deactivated_users(query) do
deactivated_users =
from(u in User.Query.build(%{deactivated: true}), select: u.ap_id)
|> Repo.all()
Activity.Queries.exclude_authors(query, deactivated_users)
end
defdelegate search(user, query, options \\ []), to: Pleroma.Activity.Search
def direct_conversation_id(activity, for_user) do
alias Pleroma.Conversation.Participation
with %{data: %{"context" => context}} when is_binary(context) <- activity,
%Pleroma.Conversation{} = conversation <- Pleroma.Conversation.get_for_ap_id(context),
%Participation{id: participation_id} <-
Participation.for_user_and_conversation(for_user, conversation) do
participation_id
else
_ -> nil
end
end
@spec pinned_by_actor?(Activity.t()) :: boolean()
def pinned_by_actor?(%Activity{} = activity) do
actor = user_actor(activity)
activity.id in actor.pinned_activities
end
@spec get_by_object_ap_id_with_object(String.t()) :: t() | nil
def get_by_object_ap_id_with_object(ap_id) when is_binary(ap_id) do
ap_id
|> Queries.by_object_id()
|> with_preloaded_object()
|> first()
|> Repo.one()
end
def get_by_object_ap_id_with_object(_), do: nil
end
diff --git a/lib/pleroma/moderation_log.ex b/lib/pleroma/moderation_log.ex
index 142dd8e0a..a7f26793d 100644
--- a/lib/pleroma/moderation_log.ex
+++ b/lib/pleroma/moderation_log.ex
@@ -1,679 +1,584 @@
# Pleroma: A lightweight social networking server
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.ModerationLog do
use Ecto.Schema
alias Pleroma.Activity
alias Pleroma.ModerationLog
alias Pleroma.Repo
alias Pleroma.User
import Ecto.Query
+ @type t :: %__MODULE__{}
+ @type log_subject :: Activity.t() | User.t() | list(User.t())
+ @type log_params :: %{
+ required(:actor) => User.t(),
+ required(:action) => String.t(),
+ optional(:subject) => log_subject(),
+ optional(:subject_actor) => User.t(),
+ optional(:subject_id) => String.t(),
+ optional(:subjects) => list(User.t()),
+ optional(:permission) => String.t(),
+ optional(:text) => String.t(),
+ optional(:sensitive) => String.t(),
+ optional(:visibility) => String.t(),
+ optional(:followed) => User.t(),
+ optional(:follower) => User.t(),
+ optional(:nicknames) => list(String.t()),
+ optional(:tags) => list(String.t()),
+ optional(:target) => String.t()
+ }
+
schema "moderation_log" do
field(:data, :map)
timestamps()
end
def get_all(params) do
base_query =
get_all_query()
|> maybe_filter_by_date(params)
|> maybe_filter_by_user(params)
|> maybe_filter_by_search(params)
query_with_pagination = base_query |> paginate_query(params)
%{
items: Repo.all(query_with_pagination),
count: Repo.aggregate(base_query, :count, :id)
}
end
defp maybe_filter_by_date(query, %{start_date: nil, end_date: nil}), do: query
defp maybe_filter_by_date(query, %{start_date: start_date, end_date: nil}) do
from(q in query,
where: q.inserted_at >= ^parse_datetime(start_date)
)
end
defp maybe_filter_by_date(query, %{start_date: nil, end_date: end_date}) do
from(q in query,
where: q.inserted_at <= ^parse_datetime(end_date)
)
end
defp maybe_filter_by_date(query, %{start_date: start_date, end_date: end_date}) do
from(q in query,
where: q.inserted_at >= ^parse_datetime(start_date),
where: q.inserted_at <= ^parse_datetime(end_date)
)
end
defp maybe_filter_by_user(query, %{user_id: nil}), do: query
defp maybe_filter_by_user(query, %{user_id: user_id}) do
from(q in query,
where: fragment("(?)->'actor'->>'id' = ?", q.data, ^user_id)
)
end
defp maybe_filter_by_search(query, %{search: search}) when is_nil(search) or search == "",
do: query
defp maybe_filter_by_search(query, %{search: search}) do
from(q in query,
where: fragment("(?)->>'message' ILIKE ?", q.data, ^"%#{search}%")
)
end
defp paginate_query(query, %{page: page, page_size: page_size}) do
from(q in query,
limit: ^page_size,
offset: ^((page - 1) * page_size)
)
end
defp get_all_query do
from(q in __MODULE__,
order_by: [desc: q.inserted_at]
)
end
defp parse_datetime(datetime) do
{:ok, parsed_datetime, _} = DateTime.from_iso8601(datetime)
parsed_datetime
end
- @spec insert_log(%{actor: User, subject: [User], action: String.t(), permission: String.t()}) ::
- {:ok, ModerationLog} | {:error, any}
- def insert_log(%{
- actor: %User{} = actor,
- subject: subjects,
- action: action,
- permission: permission
- }) do
- %ModerationLog{
- data: %{
- "actor" => user_to_map(actor),
- "subject" => user_to_map(subjects),
- "action" => action,
- "permission" => permission,
- "message" => ""
- }
+ defp prepare_log_data(%{actor: actor, action: action} = attrs) do
+ %{
+ "actor" => user_to_map(actor),
+ "action" => action,
+ "message" => ""
}
- |> insert_log_entry_with_message()
- end
+ |> Pleroma.Maps.put_if_present("subject_actor", user_to_map(attrs[:subject_actor]))
+ end
+
+ defp prepare_log_data(attrs), do: attrs
+
+ @spec insert_log(log_params()) :: {:ok, ModerationLog} | {:error, any}
+ def insert_log(%{actor: %User{}, subject: subjects, permission: permission} = attrs) do
+ data =
+ attrs
+ |> prepare_log_data
+ |> Map.merge(%{"subject" => user_to_map(subjects), "permission" => permission})
+
+ insert_log_entry_with_message(%ModerationLog{data: data})
+ end
+
+ def insert_log(%{actor: %User{}, action: action, subject: %Activity{} = subject} = attrs)
+ when action in ["report_note_delete", "report_update", "report_note"] do
+ data =
+ attrs
+ |> prepare_log_data
+ |> Pleroma.Maps.put_if_present("text", attrs[:text])
+ |> Map.merge(%{"subject" => report_to_map(subject)})
+
+ insert_log_entry_with_message(%ModerationLog{data: data})
+ end
+
+ def insert_log(
+ %{
+ actor: %User{},
+ action: action,
+ subject: %Activity{} = subject,
+ sensitive: sensitive,
+ visibility: visibility
+ } = attrs
+ )
+ when action == "status_update" do
+ data =
+ attrs
+ |> prepare_log_data
+ |> Map.merge(%{
+ "subject" => status_to_map(subject),
+ "sensitive" => sensitive,
+ "visibility" => visibility
+ })
- @spec insert_log(%{actor: User, subject: User, action: String.t()}) ::
- {:ok, ModerationLog} | {:error, any}
- def insert_log(%{
- actor: %User{} = actor,
- action: "report_update",
- subject: %Activity{data: %{"type" => "Flag"}} = subject
- }) do
- %ModerationLog{
- data: %{
- "actor" => user_to_map(actor),
- "action" => "report_update",
- "subject" => report_to_map(subject),
- "message" => ""
- }
- }
- |> insert_log_entry_with_message()
+ insert_log_entry_with_message(%ModerationLog{data: data})
end
- @spec insert_log(%{actor: User, subject: Activity, action: String.t(), text: String.t()}) ::
- {:ok, ModerationLog} | {:error, any}
- def insert_log(%{
- actor: %User{} = actor,
- action: "report_note",
- subject: %Activity{} = subject,
- text: text
- }) do
- %ModerationLog{
- data: %{
- "actor" => user_to_map(actor),
- "action" => "report_note",
- "subject" => report_to_map(subject),
- "text" => text
- }
- }
- |> insert_log_entry_with_message()
- end
+ def insert_log(%{actor: %User{}, action: action, subject_id: subject_id} = attrs)
+ when action == "status_delete" do
+ data =
+ attrs
+ |> prepare_log_data
+ |> Map.merge(%{"subject_id" => subject_id})
- @spec insert_log(%{actor: User, subject: Activity, action: String.t(), text: String.t()}) ::
- {:ok, ModerationLog} | {:error, any}
- def insert_log(%{
- actor: %User{} = actor,
- action: "report_note_delete",
- subject: %Activity{} = subject,
- text: text
- }) do
- %ModerationLog{
- data: %{
- "actor" => user_to_map(actor),
- "action" => "report_note_delete",
- "subject" => report_to_map(subject),
- "text" => text
- }
- }
- |> insert_log_entry_with_message()
+ insert_log_entry_with_message(%ModerationLog{data: data})
end
- @spec insert_log(%{
- actor: User,
- subject: Activity,
- action: String.t(),
- sensitive: String.t(),
- visibility: String.t()
- }) :: {:ok, ModerationLog} | {:error, any}
- def insert_log(%{
- actor: %User{} = actor,
- action: "status_update",
- subject: %Activity{} = subject,
- sensitive: sensitive,
- visibility: visibility
- }) do
- %ModerationLog{
- data: %{
- "actor" => user_to_map(actor),
- "action" => "status_update",
- "subject" => status_to_map(subject),
- "sensitive" => sensitive,
- "visibility" => visibility,
- "message" => ""
- }
- }
- |> insert_log_entry_with_message()
- end
+ def insert_log(%{actor: %User{}, subject: subject, action: _action} = attrs) do
+ data =
+ attrs
+ |> prepare_log_data
+ |> Map.merge(%{"subject" => user_to_map(subject)})
- @spec insert_log(%{actor: User, action: String.t(), subject_id: String.t()}) ::
- {:ok, ModerationLog} | {:error, any}
- def insert_log(%{
- actor: %User{} = actor,
- action: "status_delete",
- subject_id: subject_id
- }) do
- %ModerationLog{
- data: %{
- "actor" => user_to_map(actor),
- "action" => "status_delete",
- "subject_id" => subject_id,
- "message" => ""
- }
- }
- |> insert_log_entry_with_message()
+ insert_log_entry_with_message(%ModerationLog{data: data})
end
- @spec insert_log(%{actor: User, subject: User, action: String.t()}) ::
- {:ok, ModerationLog} | {:error, any}
- def insert_log(%{actor: %User{} = actor, subject: subject, action: action}) do
- %ModerationLog{
- data: %{
- "actor" => user_to_map(actor),
- "action" => action,
- "subject" => user_to_map(subject),
- "message" => ""
- }
- }
- |> insert_log_entry_with_message()
- end
-
- @spec insert_log(%{actor: User, subjects: [User], action: String.t()}) ::
- {:ok, ModerationLog} | {:error, any}
- def insert_log(%{actor: %User{} = actor, subjects: subjects, action: action}) do
- subjects = Enum.map(subjects, &user_to_map/1)
+ def insert_log(%{actor: %User{}, subjects: subjects, action: _action} = attrs) do
+ data =
+ attrs
+ |> prepare_log_data
+ |> Map.merge(%{"subjects" => user_to_map(subjects)})
- %ModerationLog{
- data: %{
- "actor" => user_to_map(actor),
- "action" => action,
- "subjects" => subjects,
- "message" => ""
- }
- }
- |> insert_log_entry_with_message()
+ insert_log_entry_with_message(%ModerationLog{data: data})
end
- @spec insert_log(%{actor: User, action: String.t(), followed: User, follower: User}) ::
- {:ok, ModerationLog} | {:error, any}
- def insert_log(%{
- actor: %User{} = actor,
- followed: %User{} = followed,
- follower: %User{} = follower,
- action: "follow"
- }) do
- %ModerationLog{
- data: %{
- "actor" => user_to_map(actor),
- "action" => "follow",
- "followed" => user_to_map(followed),
- "follower" => user_to_map(follower),
- "message" => ""
- }
- }
- |> insert_log_entry_with_message()
- end
+ def insert_log(
+ %{
+ actor: %User{},
+ followed: %User{} = followed,
+ follower: %User{} = follower,
+ action: action
+ } = attrs
+ )
+ when action in ["unfollow", "follow"] do
+ data =
+ attrs
+ |> prepare_log_data
+ |> Map.merge(%{"followed" => user_to_map(followed), "follower" => user_to_map(follower)})
- @spec insert_log(%{actor: User, action: String.t(), followed: User, follower: User}) ::
- {:ok, ModerationLog} | {:error, any}
- def insert_log(%{
- actor: %User{} = actor,
- followed: %User{} = followed,
- follower: %User{} = follower,
- action: "unfollow"
- }) do
- %ModerationLog{
- data: %{
- "actor" => user_to_map(actor),
- "action" => "unfollow",
- "followed" => user_to_map(followed),
- "follower" => user_to_map(follower),
- "message" => ""
- }
- }
- |> insert_log_entry_with_message()
+ insert_log_entry_with_message(%ModerationLog{data: data})
end
- @spec insert_log(%{
- actor: User,
- action: String.t(),
- nicknames: [String.t()],
- tags: [String.t()]
- }) :: {:ok, ModerationLog} | {:error, any}
def insert_log(%{
actor: %User{} = actor,
nicknames: nicknames,
tags: tags,
action: action
}) do
%ModerationLog{
data: %{
"actor" => user_to_map(actor),
"nicknames" => nicknames,
"tags" => tags,
"action" => action,
"message" => ""
}
}
|> insert_log_entry_with_message()
end
- @spec insert_log(%{actor: User, action: String.t(), target: String.t()}) ::
- {:ok, ModerationLog} | {:error, any}
- def insert_log(%{
- actor: %User{} = actor,
- action: action,
- target: target
- })
+ def insert_log(%{actor: %User{}, action: action, target: target} = attrs)
when action in ["relay_follow", "relay_unfollow"] do
- %ModerationLog{
- data: %{
- "actor" => user_to_map(actor),
- "action" => action,
- "target" => target,
- "message" => ""
- }
- }
- |> insert_log_entry_with_message()
+ data =
+ attrs
+ |> prepare_log_data
+ |> Map.merge(%{"target" => target})
+
+ insert_log_entry_with_message(%ModerationLog{data: data})
end
- @spec insert_log(%{actor: User, action: String.t(), subject_id: String.t()}) ::
- {:ok, ModerationLog} | {:error, any}
def insert_log(%{actor: %User{} = actor, action: "chat_message_delete", subject_id: subject_id}) do
%ModerationLog{
data: %{
"actor" => %{"nickname" => actor.nickname},
"action" => "chat_message_delete",
"subject_id" => subject_id
}
}
|> insert_log_entry_with_message()
end
@spec insert_log_entry_with_message(ModerationLog) :: {:ok, ModerationLog} | {:error, any}
defp insert_log_entry_with_message(entry) do
entry.data["message"]
|> put_in(get_log_entry_message(entry))
|> Repo.insert()
end
defp user_to_map(users) when is_list(users) do
- users |> Enum.map(&user_to_map/1)
+ Enum.map(users, &user_to_map/1)
end
defp user_to_map(%User{} = user) do
user
- |> Map.from_struct()
|> Map.take([:id, :nickname])
|> Map.new(fn {k, v} -> {Atom.to_string(k), v} end)
|> Map.put("type", "user")
end
+ defp user_to_map(_), do: nil
+
defp report_to_map(%Activity{} = report) do
- %{
- "type" => "report",
- "id" => report.id,
- "state" => report.data["state"]
- }
+ %{"type" => "report", "id" => report.id, "state" => report.data["state"]}
end
defp status_to_map(%Activity{} = status) do
- %{
- "type" => "status",
- "id" => status.id
- }
+ %{"type" => "status", "id" => status.id}
end
+ @spec get_log_entry_message(ModerationLog.t()) :: String.t()
def get_log_entry_message(%ModerationLog{
data: %{
"actor" => %{"nickname" => actor_nickname},
"action" => action,
"followed" => %{"nickname" => followed_nickname},
"follower" => %{"nickname" => follower_nickname}
}
}) do
"@#{actor_nickname} made @#{follower_nickname} #{action} @#{followed_nickname}"
end
- @spec get_log_entry_message(ModerationLog) :: String.t()
def get_log_entry_message(%ModerationLog{
data: %{
"actor" => %{"nickname" => actor_nickname},
"action" => "delete",
"subject" => subjects
}
}) do
"@#{actor_nickname} deleted users: #{users_to_nicknames_string(subjects)}"
end
- @spec get_log_entry_message(ModerationLog) :: String.t()
def get_log_entry_message(%ModerationLog{
data: %{
"actor" => %{"nickname" => actor_nickname},
"action" => "create",
"subjects" => subjects
}
}) do
"@#{actor_nickname} created users: #{users_to_nicknames_string(subjects)}"
end
- @spec get_log_entry_message(ModerationLog) :: String.t()
def get_log_entry_message(%ModerationLog{
data: %{
"actor" => %{"nickname" => actor_nickname},
"action" => "activate",
"subject" => users
}
}) do
"@#{actor_nickname} activated users: #{users_to_nicknames_string(users)}"
end
- @spec get_log_entry_message(ModerationLog) :: String.t()
def get_log_entry_message(%ModerationLog{
data: %{
"actor" => %{"nickname" => actor_nickname},
"action" => "deactivate",
"subject" => users
}
}) do
"@#{actor_nickname} deactivated users: #{users_to_nicknames_string(users)}"
end
- @spec get_log_entry_message(ModerationLog) :: String.t()
def get_log_entry_message(%ModerationLog{
data: %{
"actor" => %{"nickname" => actor_nickname},
"action" => "approve",
"subject" => users
}
}) do
"@#{actor_nickname} approved users: #{users_to_nicknames_string(users)}"
end
- @spec get_log_entry_message(ModerationLog) :: String.t()
def get_log_entry_message(%ModerationLog{
data: %{
"actor" => %{"nickname" => actor_nickname},
"nicknames" => nicknames,
"tags" => tags,
"action" => "tag"
}
}) do
tags_string = tags |> Enum.join(", ")
"@#{actor_nickname} added tags: #{tags_string} to users: #{nicknames_to_string(nicknames)}"
end
- @spec get_log_entry_message(ModerationLog) :: String.t()
def get_log_entry_message(%ModerationLog{
data: %{
"actor" => %{"nickname" => actor_nickname},
"nicknames" => nicknames,
"tags" => tags,
"action" => "untag"
}
}) do
tags_string = tags |> Enum.join(", ")
"@#{actor_nickname} removed tags: #{tags_string} from users: #{nicknames_to_string(nicknames)}"
end
- @spec get_log_entry_message(ModerationLog) :: String.t()
def get_log_entry_message(%ModerationLog{
data: %{
"actor" => %{"nickname" => actor_nickname},
"action" => "grant",
"subject" => users,
"permission" => permission
}
}) do
"@#{actor_nickname} made #{users_to_nicknames_string(users)} #{permission}"
end
- @spec get_log_entry_message(ModerationLog) :: String.t()
def get_log_entry_message(%ModerationLog{
data: %{
"actor" => %{"nickname" => actor_nickname},
"action" => "revoke",
"subject" => users,
"permission" => permission
}
}) do
"@#{actor_nickname} revoked #{permission} role from #{users_to_nicknames_string(users)}"
end
- @spec get_log_entry_message(ModerationLog) :: String.t()
def get_log_entry_message(%ModerationLog{
data: %{
"actor" => %{"nickname" => actor_nickname},
"action" => "relay_follow",
"target" => target
}
}) do
"@#{actor_nickname} followed relay: #{target}"
end
- @spec get_log_entry_message(ModerationLog) :: String.t()
def get_log_entry_message(%ModerationLog{
data: %{
"actor" => %{"nickname" => actor_nickname},
"action" => "relay_unfollow",
"target" => target
}
}) do
"@#{actor_nickname} unfollowed relay: #{target}"
end
- @spec get_log_entry_message(ModerationLog) :: String.t()
- def get_log_entry_message(%ModerationLog{
- data: %{
- "actor" => %{"nickname" => actor_nickname},
- "action" => "report_update",
- "subject" => %{"id" => subject_id, "state" => state, "type" => "report"}
- }
- }) do
- "@#{actor_nickname} updated report ##{subject_id} with '#{state}' state"
- end
-
- @spec get_log_entry_message(ModerationLog) :: String.t()
- def get_log_entry_message(%ModerationLog{
- data: %{
- "actor" => %{"nickname" => actor_nickname},
- "action" => "report_note",
- "subject" => %{"id" => subject_id, "type" => "report"},
- "text" => text
- }
- }) do
- "@#{actor_nickname} added note '#{text}' to report ##{subject_id}"
- end
-
- @spec get_log_entry_message(ModerationLog) :: String.t()
- def get_log_entry_message(%ModerationLog{
- data: %{
- "actor" => %{"nickname" => actor_nickname},
- "action" => "report_note_delete",
- "subject" => %{"id" => subject_id, "type" => "report"},
- "text" => text
- }
- }) do
- "@#{actor_nickname} deleted note '#{text}' from report ##{subject_id}"
+ def get_log_entry_message(
+ %ModerationLog{
+ data: %{
+ "actor" => %{"nickname" => actor_nickname},
+ "action" => "report_update",
+ "subject" => %{"id" => subject_id, "state" => state, "type" => "report"}
+ }
+ } = log
+ ) do
+ "@#{actor_nickname} updated report ##{subject_id}" <>
+ subject_actor_nickname(log, " (on user ", ")") <>
+ " with '#{state}' state"
+ end
+
+ def get_log_entry_message(
+ %ModerationLog{
+ data: %{
+ "actor" => %{"nickname" => actor_nickname},
+ "action" => "report_note",
+ "subject" => %{"id" => subject_id, "type" => "report"},
+ "text" => text
+ }
+ } = log
+ ) do
+ "@#{actor_nickname} added note '#{text}' to report ##{subject_id}" <>
+ subject_actor_nickname(log, " on user ")
+ end
+
+ def get_log_entry_message(
+ %ModerationLog{
+ data: %{
+ "actor" => %{"nickname" => actor_nickname},
+ "action" => "report_note_delete",
+ "subject" => %{"id" => subject_id, "type" => "report"},
+ "text" => text
+ }
+ } = log
+ ) do
+ "@#{actor_nickname} deleted note '#{text}' from report ##{subject_id}" <>
+ subject_actor_nickname(log, " on user ")
end
- @spec get_log_entry_message(ModerationLog) :: String.t()
def get_log_entry_message(%ModerationLog{
data: %{
"actor" => %{"nickname" => actor_nickname},
"action" => "status_update",
"subject" => %{"id" => subject_id, "type" => "status"},
"sensitive" => nil,
"visibility" => visibility
}
}) do
"@#{actor_nickname} updated status ##{subject_id}, set visibility: '#{visibility}'"
end
- @spec get_log_entry_message(ModerationLog) :: String.t()
def get_log_entry_message(%ModerationLog{
data: %{
"actor" => %{"nickname" => actor_nickname},
"action" => "status_update",
"subject" => %{"id" => subject_id, "type" => "status"},
"sensitive" => sensitive,
"visibility" => nil
}
}) do
"@#{actor_nickname} updated status ##{subject_id}, set sensitive: '#{sensitive}'"
end
- @spec get_log_entry_message(ModerationLog) :: String.t()
def get_log_entry_message(%ModerationLog{
data: %{
"actor" => %{"nickname" => actor_nickname},
"action" => "status_update",
"subject" => %{"id" => subject_id, "type" => "status"},
"sensitive" => sensitive,
"visibility" => visibility
}
}) do
"@#{actor_nickname} updated status ##{subject_id}, set sensitive: '#{sensitive}', visibility: '#{
visibility
}'"
end
- @spec get_log_entry_message(ModerationLog) :: String.t()
def get_log_entry_message(%ModerationLog{
data: %{
"actor" => %{"nickname" => actor_nickname},
"action" => "status_delete",
"subject_id" => subject_id
}
}) do
"@#{actor_nickname} deleted status ##{subject_id}"
end
- @spec get_log_entry_message(ModerationLog) :: String.t()
def get_log_entry_message(%ModerationLog{
data: %{
"actor" => %{"nickname" => actor_nickname},
"action" => "force_password_reset",
"subject" => subjects
}
}) do
"@#{actor_nickname} forced password reset for users: #{users_to_nicknames_string(subjects)}"
end
- @spec get_log_entry_message(ModerationLog) :: String.t()
def get_log_entry_message(%ModerationLog{
data: %{
"actor" => %{"nickname" => actor_nickname},
"action" => "confirm_email",
"subject" => subjects
}
}) do
"@#{actor_nickname} confirmed email for users: #{users_to_nicknames_string(subjects)}"
end
- @spec get_log_entry_message(ModerationLog) :: String.t()
def get_log_entry_message(%ModerationLog{
data: %{
"actor" => %{"nickname" => actor_nickname},
"action" => "resend_confirmation_email",
"subject" => subjects
}
}) do
"@#{actor_nickname} re-sent confirmation email for users: #{
users_to_nicknames_string(subjects)
}"
end
- @spec get_log_entry_message(ModerationLog) :: String.t()
def get_log_entry_message(%ModerationLog{
data: %{
"actor" => %{"nickname" => actor_nickname},
"action" => "updated_users",
"subject" => subjects
}
}) do
"@#{actor_nickname} updated users: #{users_to_nicknames_string(subjects)}"
end
- @spec get_log_entry_message(ModerationLog) :: String.t()
def get_log_entry_message(%ModerationLog{
data: %{
"actor" => %{"nickname" => actor_nickname},
"action" => "chat_message_delete",
"subject_id" => subject_id
}
}) do
"@#{actor_nickname} deleted chat message ##{subject_id}"
end
def get_log_entry_message(%ModerationLog{
data: %{
"actor" => %{"nickname" => actor_nickname},
"action" => "create_backup",
"subject" => %{"nickname" => user_nickname}
}
}) do
"@#{actor_nickname} requested account backup for @#{user_nickname}"
end
defp nicknames_to_string(nicknames) do
nicknames
|> Enum.map(&"@#{&1}")
|> Enum.join(", ")
end
defp users_to_nicknames_string(users) do
users
|> Enum.map(&"@#{&1["nickname"]}")
|> Enum.join(", ")
end
+
+ defp subject_actor_nickname(%ModerationLog{data: data}, prefix_msg, postfix_msg \\ "") do
+ case data do
+ %{"subject_actor" => %{"nickname" => subject_actor}} ->
+ [prefix_msg, "@#{subject_actor}", postfix_msg]
+ |> Enum.reject(&(&1 == ""))
+ |> Enum.join()
+
+ _ ->
+ ""
+ end
+ end
end
diff --git a/lib/pleroma/web/admin_api/controllers/report_controller.ex b/lib/pleroma/web/admin_api/controllers/report_controller.ex
index 6a0e56f5f..cc77cbfdf 100644
--- a/lib/pleroma/web/admin_api/controllers/report_controller.ex
+++ b/lib/pleroma/web/admin_api/controllers/report_controller.ex
@@ -1,107 +1,114 @@
# Pleroma: A lightweight social networking server
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.AdminAPI.ReportController do
use Pleroma.Web, :controller
import Pleroma.Web.ControllerHelper, only: [json_response: 3]
alias Pleroma.Activity
alias Pleroma.ModerationLog
alias Pleroma.ReportNote
alias Pleroma.Web.ActivityPub.Utils
alias Pleroma.Web.AdminAPI
alias Pleroma.Web.AdminAPI.Report
alias Pleroma.Web.CommonAPI
alias Pleroma.Web.Plugs.OAuthScopesPlug
require Logger
plug(Pleroma.Web.ApiSpec.CastAndValidate)
plug(OAuthScopesPlug, %{scopes: ["read:reports"], admin: true} when action in [:index, :show])
plug(
OAuthScopesPlug,
%{scopes: ["write:reports"], admin: true}
when action in [:update, :notes_create, :notes_delete]
)
action_fallback(AdminAPI.FallbackController)
defdelegate open_api_operation(action), to: Pleroma.Web.ApiSpec.Admin.ReportOperation
def index(conn, params) do
reports = Utils.get_reports(params, params.page, params.page_size)
render(conn, "index.json", reports: reports)
end
def show(conn, %{id: id}) do
with %Activity{} = report <- Activity.get_report(id) do
render(conn, "show.json", Report.extract_report_info(report))
else
_ -> {:error, :not_found}
end
end
def update(%{assigns: %{user: admin}, body_params: %{reports: reports}} = conn, _) do
result =
Enum.map(reports, fn report ->
case CommonAPI.update_report_state(report.id, report.state) do
{:ok, activity} ->
+ report = Activity.get_by_id_with_user_actor(activity.id)
+
ModerationLog.insert_log(%{
action: "report_update",
actor: admin,
- subject: activity
+ subject: activity,
+ subject_actor: report.user_actor
})
activity
{:error, message} ->
%{id: report.id, error: message}
end
end)
if Enum.any?(result, &Map.has_key?(&1, :error)) do
json_response(conn, :bad_request, result)
else
json_response(conn, :no_content, "")
end
end
def notes_create(%{assigns: %{user: user}, body_params: %{content: content}} = conn, %{
id: report_id
}) do
- with {:ok, _} <- ReportNote.create(user.id, report_id, content) do
+ with {:ok, _} <- ReportNote.create(user.id, report_id, content),
+ report <- Activity.get_by_id_with_user_actor(report_id) do
ModerationLog.insert_log(%{
action: "report_note",
actor: user,
- subject: Activity.get_by_id(report_id),
+ subject: report,
+ subject_actor: report.user_actor,
text: content
})
json_response(conn, :no_content, "")
else
_ -> json_response(conn, :bad_request, "")
end
end
def notes_delete(%{assigns: %{user: user}} = conn, %{
id: note_id,
report_id: report_id
}) do
- with {:ok, note} <- ReportNote.destroy(note_id) do
+ with {:ok, note} <- ReportNote.destroy(note_id),
+ report <- Activity.get_by_id_with_user_actor(report_id) do
ModerationLog.insert_log(%{
action: "report_note_delete",
actor: user,
- subject: Activity.get_by_id(report_id),
+ subject: report,
+ subject_actor: report.user_actor,
text: note.content
})
json_response(conn, :no_content, "")
else
_ -> json_response(conn, :bad_request, "")
end
end
end
diff --git a/test/pleroma/activity_test.exs b/test/pleroma/activity_test.exs
index 3e9fe209e..105f9f766 100644
--- a/test/pleroma/activity_test.exs
+++ b/test/pleroma/activity_test.exs
@@ -1,250 +1,257 @@
# Pleroma: A lightweight social networking server
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.ActivityTest do
use Pleroma.DataCase
alias Pleroma.Activity
alias Pleroma.Bookmark
alias Pleroma.Object
alias Pleroma.Tests.ObanHelpers
alias Pleroma.ThreadMute
import Pleroma.Factory
setup_all do
Tesla.Mock.mock_global(fn env -> apply(HttpRequestMock, :request, [env]) end)
:ok
end
test "returns an activity by it's AP id" do
activity = insert(:note_activity)
found_activity = Activity.get_by_ap_id(activity.data["id"])
assert activity == found_activity
end
test "returns activities by it's objects AP ids" do
activity = insert(:note_activity)
object_data = Object.normalize(activity).data
[found_activity] = Activity.get_all_create_by_object_ap_id(object_data["id"])
assert activity == found_activity
end
test "returns the activity that created an object" do
activity = insert(:note_activity)
object_data = Object.normalize(activity).data
found_activity = Activity.get_create_by_object_ap_id(object_data["id"])
assert activity == found_activity
end
test "preloading a bookmark" do
user = insert(:user)
user2 = insert(:user)
user3 = insert(:user)
activity = insert(:note_activity)
{:ok, _bookmark} = Bookmark.create(user.id, activity.id)
{:ok, _bookmark2} = Bookmark.create(user2.id, activity.id)
{:ok, bookmark3} = Bookmark.create(user3.id, activity.id)
queried_activity =
Ecto.Query.from(Pleroma.Activity)
|> Activity.with_preloaded_bookmark(user3)
|> Repo.one()
assert queried_activity.bookmark == bookmark3
end
test "setting thread_muted?" do
activity = insert(:note_activity)
user = insert(:user)
annoyed_user = insert(:user)
{:ok, _} = ThreadMute.add_mute(annoyed_user.id, activity.data["context"])
activity_with_unset_thread_muted_field =
Ecto.Query.from(Activity)
|> Repo.one()
activity_for_user =
Ecto.Query.from(Activity)
|> Activity.with_set_thread_muted_field(user)
|> Repo.one()
activity_for_annoyed_user =
Ecto.Query.from(Activity)
|> Activity.with_set_thread_muted_field(annoyed_user)
|> Repo.one()
assert activity_with_unset_thread_muted_field.thread_muted? == nil
assert activity_for_user.thread_muted? == false
assert activity_for_annoyed_user.thread_muted? == true
end
describe "getting a bookmark" do
test "when association is loaded" do
user = insert(:user)
activity = insert(:note_activity)
{:ok, bookmark} = Bookmark.create(user.id, activity.id)
queried_activity =
Ecto.Query.from(Pleroma.Activity)
|> Activity.with_preloaded_bookmark(user)
|> Repo.one()
assert Activity.get_bookmark(queried_activity, user) == bookmark
end
test "when association is not loaded" do
user = insert(:user)
activity = insert(:note_activity)
{:ok, bookmark} = Bookmark.create(user.id, activity.id)
queried_activity =
Ecto.Query.from(Pleroma.Activity)
|> Repo.one()
assert Activity.get_bookmark(queried_activity, user) == bookmark
end
end
describe "search" do
setup do
user = insert(:user)
params = %{
"@context" => "https://www.w3.org/ns/activitystreams",
"actor" => "http://mastodon.example.org/users/admin",
"type" => "Create",
"id" => "http://mastodon.example.org/users/admin/activities/1",
"object" => %{
"type" => "Note",
"content" => "find me!",
"id" => "http://mastodon.example.org/users/admin/objects/1",
"attributedTo" => "http://mastodon.example.org/users/admin"
},
"to" => ["https://www.w3.org/ns/activitystreams#Public"]
}
{:ok, local_activity} = Pleroma.Web.CommonAPI.post(user, %{status: "find me!"})
{:ok, japanese_activity} = Pleroma.Web.CommonAPI.post(user, %{status: "更新情報"})
{:ok, job} = Pleroma.Web.Federator.incoming_ap_doc(params)
{:ok, remote_activity} = ObanHelpers.perform(job)
%{
japanese_activity: japanese_activity,
local_activity: local_activity,
remote_activity: remote_activity,
user: user
}
end
setup do: clear_config([:instance, :limit_to_local_content])
test "finds utf8 text in statuses", %{
japanese_activity: japanese_activity,
user: user
} do
activities = Activity.search(user, "更新情報")
assert [^japanese_activity] = activities
end
test "find local and remote statuses for authenticated users", %{
local_activity: local_activity,
remote_activity: remote_activity,
user: user
} do
activities = Enum.sort_by(Activity.search(user, "find me"), & &1.id)
assert [^local_activity, ^remote_activity] = activities
end
test "find only local statuses for unauthenticated users", %{local_activity: local_activity} do
assert [^local_activity] = Activity.search(nil, "find me")
end
test "find only local statuses for unauthenticated users when `limit_to_local_content` is `:all`",
%{local_activity: local_activity} do
Pleroma.Config.put([:instance, :limit_to_local_content], :all)
assert [^local_activity] = Activity.search(nil, "find me")
end
test "find all statuses for unauthenticated users when `limit_to_local_content` is `false`",
%{
local_activity: local_activity,
remote_activity: remote_activity
} do
Pleroma.Config.put([:instance, :limit_to_local_content], false)
activities = Enum.sort_by(Activity.search(nil, "find me"), & &1.id)
assert [^local_activity, ^remote_activity] = activities
end
end
test "all_by_ids_with_object/1" do
%{id: id1} = insert(:note_activity)
%{id: id2} = insert(:note_activity)
activities =
[id1, id2]
|> Activity.all_by_ids_with_object()
|> Enum.sort(&(&1.id < &2.id))
assert [%{id: ^id1, object: %Object{}}, %{id: ^id2, object: %Object{}}] = activities
end
+ test "get_by_id_with_user_actor/1" do
+ user = insert(:user)
+ activity = insert(:note_activity, note: insert(:note, user: user))
+
+ assert Activity.get_by_id_with_user_actor(activity.id).user_actor == user
+ end
+
test "get_by_id_with_object/1" do
%{id: id} = insert(:note_activity)
assert %Activity{id: ^id, object: %Object{}} = Activity.get_by_id_with_object(id)
end
test "get_by_ap_id_with_object/1" do
%{data: %{"id" => ap_id}} = insert(:note_activity)
assert %Activity{data: %{"id" => ^ap_id}, object: %Object{}} =
Activity.get_by_ap_id_with_object(ap_id)
end
test "get_by_id/1" do
%{id: id} = insert(:note_activity)
assert %Activity{id: ^id} = Activity.get_by_id(id)
end
test "all_by_actor_and_id/2" do
user = insert(:user)
{:ok, %{id: id1}} = Pleroma.Web.CommonAPI.post(user, %{status: "cofe"})
{:ok, %{id: id2}} = Pleroma.Web.CommonAPI.post(user, %{status: "cofefe"})
assert [] == Activity.all_by_actor_and_id(user, [])
activities =
user.ap_id
|> Activity.all_by_actor_and_id([id1, id2])
|> Enum.sort(&(&1.id < &2.id))
assert [%Activity{id: ^id1}, %Activity{id: ^id2}] = activities
end
test "get_by_object_ap_id_with_object/1" do
user = insert(:user)
another = insert(:user)
{:ok, %{id: id, object: %{data: %{"id" => obj_id}}}} =
Pleroma.Web.CommonAPI.post(user, %{status: "cofe"})
Pleroma.Web.CommonAPI.favorite(another, id)
assert obj_id
|> Pleroma.Activity.Queries.by_object_id()
|> Repo.aggregate(:count, :id) == 2
assert %{id: ^id} = Activity.get_by_object_ap_id_with_object(obj_id)
end
end
diff --git a/test/pleroma/moderation_log_test.exs b/test/pleroma/moderation_log_test.exs
index 59f4d67f8..03b32a060 100644
--- a/test/pleroma/moderation_log_test.exs
+++ b/test/pleroma/moderation_log_test.exs
@@ -1,297 +1,313 @@
# Pleroma: A lightweight social networking server
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.ModerationLogTest do
alias Pleroma.Activity
alias Pleroma.ModerationLog
use Pleroma.DataCase
import Pleroma.Factory
describe "user moderation" do
setup do
admin = insert(:user, is_admin: true)
moderator = insert(:user, is_moderator: true)
subject1 = insert(:user)
subject2 = insert(:user)
[admin: admin, moderator: moderator, subject1: subject1, subject2: subject2]
end
test "logging user deletion by moderator", %{moderator: moderator, subject1: subject1} do
{:ok, _} =
ModerationLog.insert_log(%{
actor: moderator,
subject: [subject1],
action: "delete"
})
log = Repo.one(ModerationLog)
assert log.data["message"] == "@#{moderator.nickname} deleted users: @#{subject1.nickname}"
end
test "logging user creation by moderator", %{
moderator: moderator,
subject1: subject1,
subject2: subject2
} do
{:ok, _} =
ModerationLog.insert_log(%{
actor: moderator,
subjects: [subject1, subject2],
action: "create"
})
log = Repo.one(ModerationLog)
assert log.data["message"] ==
"@#{moderator.nickname} created users: @#{subject1.nickname}, @#{subject2.nickname}"
end
test "logging user follow by admin", %{admin: admin, subject1: subject1, subject2: subject2} do
{:ok, _} =
ModerationLog.insert_log(%{
actor: admin,
followed: subject1,
follower: subject2,
action: "follow"
})
log = Repo.one(ModerationLog)
assert log.data["message"] ==
"@#{admin.nickname} made @#{subject2.nickname} follow @#{subject1.nickname}"
end
test "logging user unfollow by admin", %{admin: admin, subject1: subject1, subject2: subject2} do
{:ok, _} =
ModerationLog.insert_log(%{
actor: admin,
followed: subject1,
follower: subject2,
action: "unfollow"
})
log = Repo.one(ModerationLog)
assert log.data["message"] ==
"@#{admin.nickname} made @#{subject2.nickname} unfollow @#{subject1.nickname}"
end
test "logging user tagged by admin", %{admin: admin, subject1: subject1, subject2: subject2} do
{:ok, _} =
ModerationLog.insert_log(%{
actor: admin,
nicknames: [subject1.nickname, subject2.nickname],
tags: ["foo", "bar"],
action: "tag"
})
log = Repo.one(ModerationLog)
users =
[subject1.nickname, subject2.nickname]
|> Enum.map(&"@#{&1}")
|> Enum.join(", ")
tags = ["foo", "bar"] |> Enum.join(", ")
assert log.data["message"] == "@#{admin.nickname} added tags: #{tags} to users: #{users}"
end
test "logging user untagged by admin", %{admin: admin, subject1: subject1, subject2: subject2} do
{:ok, _} =
ModerationLog.insert_log(%{
actor: admin,
nicknames: [subject1.nickname, subject2.nickname],
tags: ["foo", "bar"],
action: "untag"
})
log = Repo.one(ModerationLog)
users =
[subject1.nickname, subject2.nickname]
|> Enum.map(&"@#{&1}")
|> Enum.join(", ")
tags = ["foo", "bar"] |> Enum.join(", ")
assert log.data["message"] ==
"@#{admin.nickname} removed tags: #{tags} from users: #{users}"
end
test "logging user grant by moderator", %{moderator: moderator, subject1: subject1} do
{:ok, _} =
ModerationLog.insert_log(%{
actor: moderator,
subject: [subject1],
action: "grant",
permission: "moderator"
})
log = Repo.one(ModerationLog)
assert log.data["message"] == "@#{moderator.nickname} made @#{subject1.nickname} moderator"
end
test "logging user revoke by moderator", %{moderator: moderator, subject1: subject1} do
{:ok, _} =
ModerationLog.insert_log(%{
actor: moderator,
subject: [subject1],
action: "revoke",
permission: "moderator"
})
log = Repo.one(ModerationLog)
assert log.data["message"] ==
"@#{moderator.nickname} revoked moderator role from @#{subject1.nickname}"
end
test "logging relay follow", %{moderator: moderator} do
{:ok, _} =
ModerationLog.insert_log(%{
actor: moderator,
action: "relay_follow",
target: "https://example.org/relay"
})
log = Repo.one(ModerationLog)
assert log.data["message"] ==
"@#{moderator.nickname} followed relay: https://example.org/relay"
end
test "logging relay unfollow", %{moderator: moderator} do
{:ok, _} =
ModerationLog.insert_log(%{
actor: moderator,
action: "relay_unfollow",
target: "https://example.org/relay"
})
log = Repo.one(ModerationLog)
assert log.data["message"] ==
"@#{moderator.nickname} unfollowed relay: https://example.org/relay"
end
test "logging report update", %{moderator: moderator} do
+ user = insert(:user)
+
report = %Activity{
id: "9m9I1F4p8ftrTP6QTI",
data: %{
"type" => "Flag",
- "state" => "resolved"
+ "state" => "resolved",
+ "actor" => user.ap_id
}
}
{:ok, _} =
ModerationLog.insert_log(%{
actor: moderator,
action: "report_update",
- subject: report
+ subject: report,
+ subject_actor: user
})
log = Repo.one(ModerationLog)
assert log.data["message"] ==
- "@#{moderator.nickname} updated report ##{report.id} with 'resolved' state"
+ "@#{moderator.nickname} updated report ##{report.id} (on user @#{user.nickname}) with 'resolved' state"
end
test "logging report response", %{moderator: moderator} do
+ user = insert(:user)
+
report = %Activity{
id: "9m9I1F4p8ftrTP6QTI",
data: %{
- "type" => "Note"
+ "type" => "Note",
+ "actor" => user.ap_id
}
}
- {:ok, _} =
- ModerationLog.insert_log(%{
- actor: moderator,
- action: "report_note",
- subject: report,
- text: "look at this"
- })
+ attrs = %{
+ actor: moderator,
+ action: "report_note",
+ subject: report,
+ text: "look at this"
+ }
- log = Repo.one(ModerationLog)
+ {:ok, log1} = ModerationLog.insert_log(attrs)
+ log = Repo.get(ModerationLog, log1.id)
assert log.data["message"] ==
"@#{moderator.nickname} added note 'look at this' to report ##{report.id}"
+
+ {:ok, log2} = ModerationLog.insert_log(Map.merge(attrs, %{subject_actor: user}))
+
+ log = Repo.get(ModerationLog, log2.id)
+
+ assert log.data["message"] ==
+ "@#{moderator.nickname} added note 'look at this' to report ##{report.id} on user @#{
+ user.nickname
+ }"
end
test "logging status sensitivity update", %{moderator: moderator} do
note = insert(:note_activity)
{:ok, _} =
ModerationLog.insert_log(%{
actor: moderator,
action: "status_update",
subject: note,
sensitive: "true",
visibility: nil
})
log = Repo.one(ModerationLog)
assert log.data["message"] ==
"@#{moderator.nickname} updated status ##{note.id}, set sensitive: 'true'"
end
test "logging status visibility update", %{moderator: moderator} do
note = insert(:note_activity)
{:ok, _} =
ModerationLog.insert_log(%{
actor: moderator,
action: "status_update",
subject: note,
sensitive: nil,
visibility: "private"
})
log = Repo.one(ModerationLog)
assert log.data["message"] ==
"@#{moderator.nickname} updated status ##{note.id}, set visibility: 'private'"
end
test "logging status sensitivity & visibility update", %{moderator: moderator} do
note = insert(:note_activity)
{:ok, _} =
ModerationLog.insert_log(%{
actor: moderator,
action: "status_update",
subject: note,
sensitive: "true",
visibility: "private"
})
log = Repo.one(ModerationLog)
assert log.data["message"] ==
"@#{moderator.nickname} updated status ##{note.id}, set sensitive: 'true', visibility: 'private'"
end
test "logging status deletion", %{moderator: moderator} do
note = insert(:note_activity)
{:ok, _} =
ModerationLog.insert_log(%{
actor: moderator,
action: "status_delete",
subject_id: note.id
})
log = Repo.one(ModerationLog)
assert log.data["message"] == "@#{moderator.nickname} deleted status ##{note.id}"
end
end
end
diff --git a/test/pleroma/web/admin_api/controllers/report_controller_test.exs b/test/pleroma/web/admin_api/controllers/report_controller_test.exs
index 958e1d3ab..cbfc2e7b0 100644
--- a/test/pleroma/web/admin_api/controllers/report_controller_test.exs
+++ b/test/pleroma/web/admin_api/controllers/report_controller_test.exs
@@ -1,380 +1,382 @@
# Pleroma: A lightweight social networking server
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.AdminAPI.ReportControllerTest do
use Pleroma.Web.ConnCase
import Pleroma.Factory
alias Pleroma.Activity
alias Pleroma.ModerationLog
alias Pleroma.Repo
alias Pleroma.ReportNote
alias Pleroma.Web.CommonAPI
setup do
admin = insert(:user, is_admin: true)
token = insert(:oauth_admin_token, user: admin)
conn =
build_conn()
|> assign(:user, admin)
|> assign(:token, token)
{:ok, %{admin: admin, token: token, conn: conn}}
end
describe "GET /api/pleroma/admin/reports/:id" do
test "returns report by its id", %{conn: conn} do
[reporter, target_user] = insert_pair(:user)
activity = insert(:note_activity, user: target_user)
{:ok, %{id: report_id}} =
CommonAPI.report(reporter, %{
account_id: target_user.id,
comment: "I feel offended",
status_ids: [activity.id]
})
conn
|> put_req_header("content-type", "application/json")
|> post("/api/pleroma/admin/reports/#{report_id}/notes", %{
content: "this is an admin note"
})
response =
conn
|> get("/api/pleroma/admin/reports/#{report_id}")
|> json_response_and_validate_schema(:ok)
assert response["id"] == report_id
[notes] = response["notes"]
assert notes["content"] == "this is an admin note"
end
test "returns 404 when report id is invalid", %{conn: conn} do
conn = get(conn, "/api/pleroma/admin/reports/test")
assert json_response_and_validate_schema(conn, :not_found) == %{"error" => "Not found"}
end
end
describe "PATCH /api/pleroma/admin/reports" do
setup do
[reporter, target_user] = insert_pair(:user)
activity = insert(:note_activity, user: target_user)
{:ok, %{id: report_id}} =
CommonAPI.report(reporter, %{
account_id: target_user.id,
comment: "I feel offended",
status_ids: [activity.id]
})
{:ok, %{id: second_report_id}} =
CommonAPI.report(reporter, %{
account_id: target_user.id,
comment: "I feel very offended",
status_ids: [activity.id]
})
%{
id: report_id,
second_report_id: second_report_id
}
end
test "requires admin:write:reports scope", %{conn: conn, id: id, admin: admin} do
read_token = insert(:oauth_token, user: admin, scopes: ["admin:read"])
write_token = insert(:oauth_token, user: admin, scopes: ["admin:write:reports"])
response =
conn
|> assign(:token, read_token)
|> put_req_header("content-type", "application/json")
|> patch("/api/pleroma/admin/reports", %{
"reports" => [%{"state" => "resolved", "id" => id}]
})
|> json_response_and_validate_schema(403)
assert response == %{
"error" => "Insufficient permissions: admin:write:reports."
}
conn
|> assign(:token, write_token)
|> put_req_header("content-type", "application/json")
|> patch("/api/pleroma/admin/reports", %{
"reports" => [%{"state" => "resolved", "id" => id}]
})
|> json_response_and_validate_schema(:no_content)
end
test "mark report as resolved", %{conn: conn, id: id, admin: admin} do
conn
|> put_req_header("content-type", "application/json")
|> patch("/api/pleroma/admin/reports", %{
"reports" => [
%{"state" => "resolved", "id" => id}
]
})
|> json_response_and_validate_schema(:no_content)
- activity = Activity.get_by_id(id)
+ activity = Activity.get_by_id_with_user_actor(id)
assert activity.data["state"] == "resolved"
log_entry = Repo.one(ModerationLog)
assert ModerationLog.get_log_entry_message(log_entry) ==
- "@#{admin.nickname} updated report ##{id} with 'resolved' state"
+ "@#{admin.nickname} updated report ##{id} (on user @#{activity.user_actor.nickname}) with 'resolved' state"
end
test "closes report", %{conn: conn, id: id, admin: admin} do
conn
|> put_req_header("content-type", "application/json")
|> patch("/api/pleroma/admin/reports", %{
"reports" => [
%{"state" => "closed", "id" => id}
]
})
|> json_response_and_validate_schema(:no_content)
- activity = Activity.get_by_id(id)
+ activity = Activity.get_by_id_with_user_actor(id)
assert activity.data["state"] == "closed"
log_entry = Repo.one(ModerationLog)
assert ModerationLog.get_log_entry_message(log_entry) ==
- "@#{admin.nickname} updated report ##{id} with 'closed' state"
+ "@#{admin.nickname} updated report ##{id} (on user @#{activity.user_actor.nickname}) with 'closed' state"
end
test "returns 400 when state is unknown", %{conn: conn, id: id} do
conn =
conn
|> put_req_header("content-type", "application/json")
|> patch("/api/pleroma/admin/reports", %{
"reports" => [
%{"state" => "test", "id" => id}
]
})
assert "Unsupported state" =
hd(json_response_and_validate_schema(conn, :bad_request))["error"]
end
test "returns 404 when report is not exist", %{conn: conn} do
conn =
conn
|> put_req_header("content-type", "application/json")
|> patch("/api/pleroma/admin/reports", %{
"reports" => [
%{"state" => "closed", "id" => "test"}
]
})
assert hd(json_response_and_validate_schema(conn, :bad_request))["error"] == "not_found"
end
test "updates state of multiple reports", %{
conn: conn,
id: id,
admin: admin,
second_report_id: second_report_id
} do
conn
|> put_req_header("content-type", "application/json")
|> patch("/api/pleroma/admin/reports", %{
"reports" => [
%{"state" => "resolved", "id" => id},
%{"state" => "closed", "id" => second_report_id}
]
})
|> json_response_and_validate_schema(:no_content)
- activity = Activity.get_by_id(id)
- second_activity = Activity.get_by_id(second_report_id)
+ activity = Activity.get_by_id_with_user_actor(id)
+ second_activity = Activity.get_by_id_with_user_actor(second_report_id)
assert activity.data["state"] == "resolved"
assert second_activity.data["state"] == "closed"
[first_log_entry, second_log_entry] = Repo.all(ModerationLog)
assert ModerationLog.get_log_entry_message(first_log_entry) ==
- "@#{admin.nickname} updated report ##{id} with 'resolved' state"
+ "@#{admin.nickname} updated report ##{id} (on user @#{activity.user_actor.nickname}) with 'resolved' state"
assert ModerationLog.get_log_entry_message(second_log_entry) ==
- "@#{admin.nickname} updated report ##{second_report_id} with 'closed' state"
+ "@#{admin.nickname} updated report ##{second_report_id} (on user @#{
+ second_activity.user_actor.nickname
+ }) with 'closed' state"
end
end
describe "GET /api/pleroma/admin/reports" do
test "returns empty response when no reports created", %{conn: conn} do
response =
conn
|> get(report_path(conn, :index))
|> json_response_and_validate_schema(:ok)
assert Enum.empty?(response["reports"])
assert response["total"] == 0
end
test "returns reports", %{conn: conn} do
[reporter, target_user] = insert_pair(:user)
activity = insert(:note_activity, user: target_user)
{:ok, %{id: report_id}} =
CommonAPI.report(reporter, %{
account_id: target_user.id,
comment: "I feel offended",
status_ids: [activity.id]
})
response =
conn
|> get(report_path(conn, :index))
|> json_response_and_validate_schema(:ok)
[report] = response["reports"]
assert length(response["reports"]) == 1
assert report["id"] == report_id
assert response["total"] == 1
end
test "returns reports with specified state", %{conn: conn} do
[reporter, target_user] = insert_pair(:user)
activity = insert(:note_activity, user: target_user)
{:ok, %{id: first_report_id}} =
CommonAPI.report(reporter, %{
account_id: target_user.id,
comment: "I feel offended",
status_ids: [activity.id]
})
{:ok, %{id: second_report_id}} =
CommonAPI.report(reporter, %{
account_id: target_user.id,
comment: "I don't like this user"
})
CommonAPI.update_report_state(second_report_id, "closed")
response =
conn
|> get(report_path(conn, :index, %{state: "open"}))
|> json_response_and_validate_schema(:ok)
assert [open_report] = response["reports"]
assert length(response["reports"]) == 1
assert open_report["id"] == first_report_id
assert response["total"] == 1
response =
conn
|> get(report_path(conn, :index, %{state: "closed"}))
|> json_response_and_validate_schema(:ok)
assert [closed_report] = response["reports"]
assert length(response["reports"]) == 1
assert closed_report["id"] == second_report_id
assert response["total"] == 1
assert %{"total" => 0, "reports" => []} ==
conn
|> get(report_path(conn, :index, %{state: "resolved"}))
|> json_response_and_validate_schema(:ok)
end
test "returns 403 when requested by a non-admin" do
user = insert(:user)
token = insert(:oauth_token, user: user)
conn =
build_conn()
|> assign(:user, user)
|> assign(:token, token)
|> get("/api/pleroma/admin/reports")
assert json_response(conn, :forbidden) ==
%{"error" => "User is not an admin."}
end
test "returns 403 when requested by anonymous" do
conn = get(build_conn(), "/api/pleroma/admin/reports")
assert json_response(conn, :forbidden) == %{
"error" => "Invalid credentials."
}
end
end
describe "POST /api/pleroma/admin/reports/:id/notes" do
setup %{conn: conn, admin: admin} do
[reporter, target_user] = insert_pair(:user)
activity = insert(:note_activity, user: target_user)
{:ok, %{id: report_id}} =
CommonAPI.report(reporter, %{
account_id: target_user.id,
comment: "I feel offended",
status_ids: [activity.id]
})
conn
|> put_req_header("content-type", "application/json")
|> post("/api/pleroma/admin/reports/#{report_id}/notes", %{
content: "this is disgusting!"
})
conn
|> put_req_header("content-type", "application/json")
|> post("/api/pleroma/admin/reports/#{report_id}/notes", %{
content: "this is disgusting2!"
})
%{
admin_id: admin.id,
report_id: report_id
}
end
test "it creates report note", %{admin_id: admin_id, report_id: report_id} do
assert [note, _] = Repo.all(ReportNote)
assert %{
activity_id: ^report_id,
content: "this is disgusting!",
user_id: ^admin_id
} = note
end
test "it returns reports with notes", %{conn: conn, admin: admin} do
conn = get(conn, "/api/pleroma/admin/reports")
response = json_response_and_validate_schema(conn, 200)
notes = hd(response["reports"])["notes"]
[note, _] = notes
assert note["user"]["nickname"] == admin.nickname
assert note["content"] == "this is disgusting!"
assert note["created_at"]
assert response["total"] == 1
end
test "it deletes the note", %{conn: conn, report_id: report_id} do
assert ReportNote |> Repo.all() |> length() == 2
assert [note, _] = Repo.all(ReportNote)
delete(conn, "/api/pleroma/admin/reports/#{report_id}/notes/#{note.id}")
assert ReportNote |> Repo.all() |> length() == 1
end
end
end
diff --git a/test/pleroma/web/admin_api/views/moderation_log_view_test.exs b/test/pleroma/web/admin_api/views/moderation_log_view_test.exs
new file mode 100644
index 000000000..e6c5aaa7f
--- /dev/null
+++ b/test/pleroma/web/admin_api/views/moderation_log_view_test.exs
@@ -0,0 +1,98 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
+# SPDX-License-Identifier: AGPL-3.0-only
+defmodule Pleroma.Web.AdminAPI.ModerationLogViewTest do
+ use Pleroma.DataCase
+
+ alias Pleroma.Web.AdminAPI.ModerationLogView
+
+ describe "renders `report_note_delete` log messages" do
+ setup do
+ log1 = %Pleroma.ModerationLog{
+ data: %{
+ "action" => "report_note_delete",
+ "actor" => %{"id" => "A1I7G8", "nickname" => "admin", "type" => "user"},
+ "message" => "@admin deleted note 'mistake' from report #A1I7be on user @b-612",
+ "subject" => %{"id" => "A1I7be", "state" => "open", "type" => "report"},
+ "subject_actor" => %{"id" => "A1I7G8", "nickname" => "b-612", "type" => "user"},
+ "text" => "mistake"
+ },
+ inserted_at: ~N[2020-11-17 14:13:20]
+ }
+
+ log2 = %Pleroma.ModerationLog{
+ data: %{
+ "action" => "report_note_delete",
+ "actor" => %{"id" => "A1I7G8", "nickname" => "admin", "type" => "user"},
+ "message" => "@admin deleted note 'fake user' from report #A1I7be on user @j-612",
+ "subject" => %{"id" => "A1I7be", "state" => "open", "type" => "report"},
+ "subject_actor" => %{"id" => "A1I7G8", "nickname" => "j-612", "type" => "user"},
+ "text" => "fake user"
+ },
+ inserted_at: ~N[2020-11-17 14:13:20]
+ }
+
+ {:ok, %{log1: log1, log2: log2}}
+ end
+
+ test "renders `report_note_delete` log messages", %{log1: log1, log2: log2} do
+ assert ModerationLogView.render(
+ "index.json",
+ %{log: %{items: [log1, log2], count: 2}}
+ ) == %{
+ items: [
+ %{
+ data: %{
+ "action" => "report_note_delete",
+ "actor" => %{"id" => "A1I7G8", "nickname" => "admin", "type" => "user"},
+ "message" =>
+ "@admin deleted note 'mistake' from report #A1I7be on user @b-612",
+ "subject" => %{"id" => "A1I7be", "state" => "open", "type" => "report"},
+ "subject_actor" => %{
+ "id" => "A1I7G8",
+ "nickname" => "b-612",
+ "type" => "user"
+ },
+ "text" => "mistake"
+ },
+ message: "@admin deleted note 'mistake' from report #A1I7be on user @b-612",
+ time: 1_605_622_400
+ },
+ %{
+ data: %{
+ "action" => "report_note_delete",
+ "actor" => %{"id" => "A1I7G8", "nickname" => "admin", "type" => "user"},
+ "message" =>
+ "@admin deleted note 'fake user' from report #A1I7be on user @j-612",
+ "subject" => %{"id" => "A1I7be", "state" => "open", "type" => "report"},
+ "subject_actor" => %{
+ "id" => "A1I7G8",
+ "nickname" => "j-612",
+ "type" => "user"
+ },
+ "text" => "fake user"
+ },
+ message: "@admin deleted note 'fake user' from report #A1I7be on user @j-612",
+ time: 1_605_622_400
+ }
+ ],
+ total: 2
+ }
+ end
+
+ test "renders `report_note_delete` log message", %{log1: log} do
+ assert ModerationLogView.render("show.json", %{log_entry: log}) == %{
+ data: %{
+ "action" => "report_note_delete",
+ "actor" => %{"id" => "A1I7G8", "nickname" => "admin", "type" => "user"},
+ "message" => "@admin deleted note 'mistake' from report #A1I7be on user @b-612",
+ "subject" => %{"id" => "A1I7be", "state" => "open", "type" => "report"},
+ "subject_actor" => %{"id" => "A1I7G8", "nickname" => "b-612", "type" => "user"},
+ "text" => "mistake"
+ },
+ message: "@admin deleted note 'mistake' from report #A1I7be on user @b-612",
+ time: 1_605_622_400
+ }
+ end
+ end
+end

File Metadata

Mime Type
text/x-diff
Expires
Mon, Nov 25, 5:39 AM (1 d, 10 h)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
39635
Default Alt Text
(75 KB)

Event Timeline