aboutsummaryrefslogtreecommitdiff
path: root/lib/pleroma/web
diff options
context:
space:
mode:
Diffstat (limited to 'lib/pleroma/web')
-rw-r--r--lib/pleroma/web/activity_pub/activity_pub.ex343
-rw-r--r--lib/pleroma/web/activity_pub/activity_pub_controller.ex8
-rw-r--r--lib/pleroma/web/activity_pub/builder.ex34
-rw-r--r--lib/pleroma/web/activity_pub/mrf.ex4
-rw-r--r--lib/pleroma/web/activity_pub/mrf/follow_bot_policy.ex59
-rw-r--r--lib/pleroma/web/activity_pub/mrf/hashtag_policy.ex116
-rw-r--r--lib/pleroma/web/activity_pub/mrf/simple_policy.ex34
-rw-r--r--lib/pleroma/web/activity_pub/mrf/tag_policy.ex13
-rw-r--r--lib/pleroma/web/activity_pub/object_validator.ex173
-rw-r--r--lib/pleroma/web/activity_pub/object_validators/accept_reject_validator.ex2
-rw-r--r--lib/pleroma/web/activity_pub/object_validators/add_remove_validator.ex77
-rw-r--r--lib/pleroma/web/activity_pub/object_validators/announce_validator.ex4
-rw-r--r--lib/pleroma/web/activity_pub/object_validators/answer_validator.ex9
-rw-r--r--lib/pleroma/web/activity_pub/object_validators/article_note_validator.ex41
-rw-r--r--lib/pleroma/web/activity_pub/object_validators/attachment_validator.ex7
-rw-r--r--lib/pleroma/web/activity_pub/object_validators/audio_video_validator.ex15
-rw-r--r--lib/pleroma/web/activity_pub/object_validators/block_validator.ex2
-rw-r--r--lib/pleroma/web/activity_pub/object_validators/chat_message_validator.ex2
-rw-r--r--lib/pleroma/web/activity_pub/object_validators/common_fixes.ex41
-rw-r--r--lib/pleroma/web/activity_pub/object_validators/common_validations.ex9
-rw-r--r--lib/pleroma/web/activity_pub/object_validators/create_chat_message_validator.ex2
-rw-r--r--lib/pleroma/web/activity_pub/object_validators/create_generic_validator.ex69
-rw-r--r--lib/pleroma/web/activity_pub/object_validators/create_note_validator.ex29
-rw-r--r--lib/pleroma/web/activity_pub/object_validators/delete_validator.ex2
-rw-r--r--lib/pleroma/web/activity_pub/object_validators/emoji_react_validator.ex2
-rw-r--r--lib/pleroma/web/activity_pub/object_validators/event_validator.ex13
-rw-r--r--lib/pleroma/web/activity_pub/object_validators/follow_validator.ex2
-rw-r--r--lib/pleroma/web/activity_pub/object_validators/like_validator.ex2
-rw-r--r--lib/pleroma/web/activity_pub/object_validators/question_validator.ex13
-rw-r--r--lib/pleroma/web/activity_pub/object_validators/tag_validator.ex77
-rw-r--r--lib/pleroma/web/activity_pub/object_validators/undo_validator.ex2
-rw-r--r--lib/pleroma/web/activity_pub/object_validators/update_validator.ex2
-rw-r--r--lib/pleroma/web/activity_pub/pipeline.ex30
-rw-r--r--lib/pleroma/web/activity_pub/side_effects.ex76
-rw-r--r--lib/pleroma/web/activity_pub/transmogrifier.ex135
-rw-r--r--lib/pleroma/web/activity_pub/utils.ex9
-rw-r--r--lib/pleroma/web/activity_pub/views/user_view.ex22
-rw-r--r--lib/pleroma/web/activity_pub/visibility.ex6
-rw-r--r--lib/pleroma/web/admin_api/controllers/user_controller.ex128
-rw-r--r--lib/pleroma/web/admin_api/views/account_view.ex19
-rw-r--r--lib/pleroma/web/api_spec.ex5
-rw-r--r--lib/pleroma/web/api_spec/cast_and_validate.ex31
-rw-r--r--lib/pleroma/web/api_spec/operations/admin/user_operation.ex389
-rw-r--r--lib/pleroma/web/api_spec/operations/status_operation.ex48
-rw-r--r--lib/pleroma/web/api_spec/schemas/boolean_like.ex10
-rw-r--r--lib/pleroma/web/api_spec/schemas/status.ex7
-rw-r--r--lib/pleroma/web/common_api.ex73
-rw-r--r--lib/pleroma/web/common_api/activity_draft.ex29
-rw-r--r--lib/pleroma/web/common_api/utils.ex12
-rw-r--r--lib/pleroma/web/federator.ex5
-rw-r--r--lib/pleroma/web/feed/feed_view.ex1
-rw-r--r--lib/pleroma/web/mastodon_api/controllers/fallback_controller.ex6
-rw-r--r--lib/pleroma/web/mastodon_api/controllers/instance_controller.ex2
-rw-r--r--lib/pleroma/web/mastodon_api/controllers/status_controller.ex32
-rw-r--r--lib/pleroma/web/mastodon_api/controllers/timeline_controller.ex43
-rw-r--r--lib/pleroma/web/mastodon_api/views/account_view.ex11
-rw-r--r--lib/pleroma/web/mastodon_api/views/instance_view.ex4
-rw-r--r--lib/pleroma/web/mastodon_api/views/status_view.ex93
-rw-r--r--lib/pleroma/web/media_proxy.ex5
-rw-r--r--lib/pleroma/web/o_auth/o_auth_view.ex1
-rw-r--r--lib/pleroma/web/pleroma_api/controllers/backup_controller.ex2
-rw-r--r--lib/pleroma/web/pleroma_api/controllers/chat_controller.ex2
-rw-r--r--lib/pleroma/web/pleroma_api/controllers/user_import_controller.ex2
-rw-r--r--lib/pleroma/web/plugs/frontend_static.ex9
-rw-r--r--lib/pleroma/web/plugs/http_security_plug.ex3
-rw-r--r--lib/pleroma/web/router.ex3
-rw-r--r--lib/pleroma/web/templates/feed/feed/_activity.atom.eex2
-rw-r--r--lib/pleroma/web/templates/feed/feed/_activity.rss.eex2
-rw-r--r--lib/pleroma/web/templates/feed/feed/_tag_activity.atom.eex2
-rw-r--r--lib/pleroma/web/web_finger.ex98
-rw-r--r--lib/pleroma/web/xml.ex2
71 files changed, 1897 insertions, 670 deletions
diff --git a/lib/pleroma/web/activity_pub/activity_pub.ex b/lib/pleroma/web/activity_pub/activity_pub.ex
index 5b45e2ca1..18368943d 100644
--- a/lib/pleroma/web/activity_pub/activity_pub.ex
+++ b/lib/pleroma/web/activity_pub/activity_pub.ex
@@ -10,6 +10,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do
alias Pleroma.Conversation
alias Pleroma.Conversation.Participation
alias Pleroma.Filter
+ alias Pleroma.Hashtag
alias Pleroma.Maps
alias Pleroma.Notification
alias Pleroma.Object
@@ -87,7 +88,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do
defp increase_replies_count_if_reply(_create_data), do: :noop
- @object_types ~w[ChatMessage Question Answer Audio Video Event Article]
+ @object_types ~w[ChatMessage Question Answer Audio Video Event Article Note]
@impl true
def persist(%{"type" => type} = object, meta) when type in @object_types do
with {:ok, object} <- Object.create(object) do
@@ -465,6 +466,23 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do
|> Repo.one()
end
+ defp fetch_paginated_optimized(query, opts, pagination) do
+ # Note: tag-filtering funcs may apply "ORDER BY objects.id DESC",
+ # and extra sorting on "activities.id DESC NULLS LAST" would worse the query plan
+ opts = Map.put(opts, :skip_extra_order, true)
+
+ Pagination.fetch_paginated(query, opts, pagination)
+ end
+
+ def fetch_activities(recipients, opts \\ %{}, pagination \\ :keyset) do
+ list_memberships = Pleroma.List.memberships(opts[:user])
+
+ fetch_activities_query(recipients ++ list_memberships, opts)
+ |> fetch_paginated_optimized(opts, pagination)
+ |> Enum.reverse()
+ |> maybe_update_cc(list_memberships, opts[:user])
+ end
+
@spec fetch_public_or_unlisted_activities(map(), Pagination.type()) :: [Activity.t()]
def fetch_public_or_unlisted_activities(opts \\ %{}, pagination \\ :keyset) do
opts = Map.delete(opts, :user)
@@ -472,7 +490,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do
[Constants.as_public()]
|> fetch_activities_query(opts)
|> restrict_unlisted(opts)
- |> Pagination.fetch_paginated(opts, pagination)
+ |> fetch_paginated_optimized(opts, pagination)
end
@spec fetch_public_activities(map(), Pagination.type()) :: [Activity.t()]
@@ -612,7 +630,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do
|> Map.put(:type, ["Create", "Announce"])
|> Map.put(:user, reading_user)
|> Map.put(:actor_id, user.ap_id)
- |> Map.put(:pinned_activity_ids, user.pinned_activities)
+ |> Map.put(:pinned_object_ids, Map.keys(user.pinned_objects))
params =
if User.blocks?(reading_user, user) do
@@ -693,51 +711,143 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do
defp restrict_since(query, _), do: query
- defp restrict_tag_reject(_query, %{tag_reject: _tag_reject, skip_preload: true}) do
- raise "Can't use the child object without preloading!"
+ defp restrict_embedded_tag_all(_query, %{tag_all: _tag_all, skip_preload: true}) do
+ raise_on_missing_preload()
+ end
+
+ defp restrict_embedded_tag_all(query, %{tag_all: [_ | _] = tag_all}) do
+ from(
+ [_activity, object] in query,
+ where: fragment("(?)->'tag' \\?& (?)", object.data, ^tag_all)
+ )
+ end
+
+ defp restrict_embedded_tag_all(query, %{tag_all: tag}) when is_binary(tag) do
+ restrict_embedded_tag_any(query, %{tag: tag})
+ end
+
+ defp restrict_embedded_tag_all(query, _), do: query
+
+ defp restrict_embedded_tag_any(_query, %{tag: _tag, skip_preload: true}) do
+ raise_on_missing_preload()
end
- defp restrict_tag_reject(query, %{tag_reject: [_ | _] = tag_reject}) do
+ defp restrict_embedded_tag_any(query, %{tag: [_ | _] = tag_any}) do
+ from(
+ [_activity, object] in query,
+ where: fragment("(?)->'tag' \\?| (?)", object.data, ^tag_any)
+ )
+ end
+
+ defp restrict_embedded_tag_any(query, %{tag: tag}) when is_binary(tag) do
+ restrict_embedded_tag_any(query, %{tag: [tag]})
+ end
+
+ defp restrict_embedded_tag_any(query, _), do: query
+
+ defp restrict_embedded_tag_reject_any(_query, %{tag_reject: _tag_reject, skip_preload: true}) do
+ raise_on_missing_preload()
+ end
+
+ defp restrict_embedded_tag_reject_any(query, %{tag_reject: [_ | _] = tag_reject}) do
from(
[_activity, object] in query,
where: fragment("not (?)->'tag' \\?| (?)", object.data, ^tag_reject)
)
end
- defp restrict_tag_reject(query, _), do: query
+ defp restrict_embedded_tag_reject_any(query, %{tag_reject: tag_reject})
+ when is_binary(tag_reject) do
+ restrict_embedded_tag_reject_any(query, %{tag_reject: [tag_reject]})
+ end
- defp restrict_tag_all(_query, %{tag_all: _tag_all, skip_preload: true}) do
- raise "Can't use the child object without preloading!"
+ defp restrict_embedded_tag_reject_any(query, _), do: query
+
+ defp object_ids_query_for_tags(tags) do
+ from(hto in "hashtags_objects")
+ |> join(:inner, [hto], ht in Pleroma.Hashtag, on: hto.hashtag_id == ht.id)
+ |> where([hto, ht], ht.name in ^tags)
+ |> select([hto], hto.object_id)
+ |> distinct([hto], true)
+ end
+
+ defp restrict_hashtag_all(_query, %{tag_all: _tag, skip_preload: true}) do
+ raise_on_missing_preload()
+ end
+
+ defp restrict_hashtag_all(query, %{tag_all: [single_tag]}) do
+ restrict_hashtag_any(query, %{tag: single_tag})
end
- defp restrict_tag_all(query, %{tag_all: [_ | _] = tag_all}) do
+ defp restrict_hashtag_all(query, %{tag_all: [_ | _] = tags}) do
from(
[_activity, object] in query,
- where: fragment("(?)->'tag' \\?& (?)", object.data, ^tag_all)
+ where:
+ fragment(
+ """
+ (SELECT array_agg(hashtags.name) FROM hashtags JOIN hashtags_objects
+ ON hashtags_objects.hashtag_id = hashtags.id WHERE hashtags.name = ANY(?)
+ AND hashtags_objects.object_id = ?) @> ?
+ """,
+ ^tags,
+ object.id,
+ ^tags
+ )
)
end
- defp restrict_tag_all(query, _), do: query
+ defp restrict_hashtag_all(query, %{tag_all: tag}) when is_binary(tag) do
+ restrict_hashtag_all(query, %{tag_all: [tag]})
+ end
- defp restrict_tag(_query, %{tag: _tag, skip_preload: true}) do
- raise "Can't use the child object without preloading!"
+ defp restrict_hashtag_all(query, _), do: query
+
+ defp restrict_hashtag_any(_query, %{tag: _tag, skip_preload: true}) do
+ raise_on_missing_preload()
end
- defp restrict_tag(query, %{tag: tag}) when is_list(tag) do
+ defp restrict_hashtag_any(query, %{tag: [_ | _] = tags}) do
+ hashtag_ids =
+ from(ht in Hashtag, where: ht.name in ^tags, select: ht.id)
+ |> Repo.all()
+
+ # Note: NO extra ordering should be done on "activities.id desc nulls last" for optimal plan
from(
[_activity, object] in query,
- where: fragment("(?)->'tag' \\?| (?)", object.data, ^tag)
+ join: hto in "hashtags_objects",
+ on: hto.object_id == object.id,
+ where: hto.hashtag_id in ^hashtag_ids,
+ distinct: [desc: object.id],
+ order_by: [desc: object.id]
)
end
- defp restrict_tag(query, %{tag: tag}) when is_binary(tag) do
+ defp restrict_hashtag_any(query, %{tag: tag}) when is_binary(tag) do
+ restrict_hashtag_any(query, %{tag: [tag]})
+ end
+
+ defp restrict_hashtag_any(query, _), do: query
+
+ defp restrict_hashtag_reject_any(_query, %{tag_reject: _tag_reject, skip_preload: true}) do
+ raise_on_missing_preload()
+ end
+
+ defp restrict_hashtag_reject_any(query, %{tag_reject: [_ | _] = tags_reject}) do
from(
[_activity, object] in query,
- where: fragment("(?)->'tag' \\? (?)", object.data, ^tag)
+ where: object.id not in subquery(object_ids_query_for_tags(tags_reject))
)
end
- defp restrict_tag(query, _), do: query
+ defp restrict_hashtag_reject_any(query, %{tag_reject: tag_reject}) when is_binary(tag_reject) do
+ restrict_hashtag_reject_any(query, %{tag_reject: [tag_reject]})
+ end
+
+ defp restrict_hashtag_reject_any(query, _), do: query
+
+ defp raise_on_missing_preload do
+ raise "Can't use the child object without preloading!"
+ end
defp restrict_recipients(query, [], _user), do: query
@@ -965,8 +1075,18 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do
defp restrict_unlisted(query, _), do: query
- defp restrict_pinned(query, %{pinned: true, pinned_activity_ids: ids}) do
- from(activity in query, where: activity.id in ^ids)
+ defp restrict_pinned(query, %{pinned: true, pinned_object_ids: ids}) do
+ from(
+ [activity, object: o] in query,
+ where:
+ fragment(
+ "(?)->>'type' = 'Create' and coalesce((?)->'object'->>'id', (?)->>'object') = any (?)",
+ activity.data,
+ activity.data,
+ activity.data,
+ ^ids
+ )
+ )
end
defp restrict_pinned(query, _), do: query
@@ -1098,6 +1218,26 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do
defp maybe_order(query, _), do: query
+ defp normalize_fetch_activities_query_opts(opts) do
+ Enum.reduce([:tag, :tag_all, :tag_reject], opts, fn key, opts ->
+ case opts[key] do
+ value when is_bitstring(value) ->
+ Map.put(opts, key, Hashtag.normalize_name(value))
+
+ value when is_list(value) ->
+ normalized_value =
+ value
+ |> Enum.map(&Hashtag.normalize_name/1)
+ |> Enum.uniq()
+
+ Map.put(opts, key, normalized_value)
+
+ _ ->
+ opts
+ end
+ end)
+ end
+
defp fetch_activities_query_ap_ids_ops(opts) do
source_user = opts[:muting_user]
ap_id_relationships = if source_user, do: [:mute, :reblog_mute], else: []
@@ -1121,6 +1261,8 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do
end
def fetch_activities_query(recipients, opts \\ %{}) do
+ opts = normalize_fetch_activities_query_opts(opts)
+
{restrict_blocked_opts, restrict_muted_opts, restrict_muted_reblogs_opts} =
fetch_activities_query_ap_ids_ops(opts)
@@ -1128,50 +1270,51 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do
skip_thread_containment: Config.get([:instance, :skip_thread_containment])
}
- Activity
- |> maybe_preload_objects(opts)
- |> maybe_preload_bookmarks(opts)
- |> maybe_preload_report_notes(opts)
- |> maybe_set_thread_muted_field(opts)
- |> maybe_order(opts)
- |> restrict_recipients(recipients, opts[:user])
- |> restrict_replies(opts)
- |> restrict_tag(opts)
- |> restrict_tag_reject(opts)
- |> restrict_tag_all(opts)
- |> restrict_since(opts)
- |> restrict_local(opts)
- |> restrict_remote(opts)
- |> restrict_actor(opts)
- |> restrict_type(opts)
- |> restrict_state(opts)
- |> restrict_favorited_by(opts)
- |> restrict_blocked(restrict_blocked_opts)
- |> restrict_muted(restrict_muted_opts)
- |> restrict_filtered(opts)
- |> restrict_media(opts)
- |> restrict_visibility(opts)
- |> restrict_thread_visibility(opts, config)
- |> restrict_reblogs(opts)
- |> restrict_pinned(opts)
- |> restrict_muted_reblogs(restrict_muted_reblogs_opts)
- |> restrict_instance(opts)
- |> restrict_announce_object_actor(opts)
- |> restrict_filtered(opts)
- |> Activity.restrict_deactivated_users()
- |> exclude_poll_votes(opts)
- |> exclude_chat_messages(opts)
- |> exclude_invisible_actors(opts)
- |> exclude_visibility(opts)
- end
-
- def fetch_activities(recipients, opts \\ %{}, pagination \\ :keyset) do
- list_memberships = Pleroma.List.memberships(opts[:user])
-
- fetch_activities_query(recipients ++ list_memberships, opts)
- |> Pagination.fetch_paginated(opts, pagination)
- |> Enum.reverse()
- |> maybe_update_cc(list_memberships, opts[:user])
+ query =
+ Activity
+ |> maybe_preload_objects(opts)
+ |> maybe_preload_bookmarks(opts)
+ |> maybe_preload_report_notes(opts)
+ |> maybe_set_thread_muted_field(opts)
+ |> maybe_order(opts)
+ |> restrict_recipients(recipients, opts[:user])
+ |> restrict_replies(opts)
+ |> restrict_since(opts)
+ |> restrict_local(opts)
+ |> restrict_remote(opts)
+ |> restrict_actor(opts)
+ |> restrict_type(opts)
+ |> restrict_state(opts)
+ |> restrict_favorited_by(opts)
+ |> restrict_blocked(restrict_blocked_opts)
+ |> restrict_muted(restrict_muted_opts)
+ |> restrict_filtered(opts)
+ |> restrict_media(opts)
+ |> restrict_visibility(opts)
+ |> restrict_thread_visibility(opts, config)
+ |> restrict_reblogs(opts)
+ |> restrict_pinned(opts)
+ |> restrict_muted_reblogs(restrict_muted_reblogs_opts)
+ |> restrict_instance(opts)
+ |> restrict_announce_object_actor(opts)
+ |> restrict_filtered(opts)
+ |> Activity.restrict_deactivated_users()
+ |> exclude_poll_votes(opts)
+ |> exclude_chat_messages(opts)
+ |> exclude_invisible_actors(opts)
+ |> exclude_visibility(opts)
+
+ if Config.feature_enabled?(:improved_hashtag_timeline) do
+ query
+ |> restrict_hashtag_any(opts)
+ |> restrict_hashtag_all(opts)
+ |> restrict_hashtag_reject_any(opts)
+ else
+ query
+ |> restrict_embedded_tag_any(opts)
+ |> restrict_embedded_tag_all(opts)
+ |> restrict_embedded_tag_reject_any(opts)
+ end
end
@doc """
@@ -1250,21 +1393,17 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do
defp get_actor_url(_url), do: nil
- defp object_to_user_data(data) do
- avatar =
- data["icon"]["url"] &&
- %{
- "type" => "Image",
- "url" => [%{"href" => data["icon"]["url"]}]
- }
+ defp normalize_image(%{"url" => url}) do
+ %{
+ "type" => "Image",
+ "url" => [%{"href" => url}]
+ }
+ end
- banner =
- data["image"]["url"] &&
- %{
- "type" => "Image",
- "url" => [%{"href" => data["image"]["url"]}]
- }
+ defp normalize_image(urls) when is_list(urls), do: urls |> List.first() |> normalize_image()
+ defp normalize_image(_), do: nil
+ defp object_to_user_data(data) do
fields =
data
|> Map.get("attachment", [])
@@ -1290,6 +1429,9 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do
invisible = data["invisible"] || false
actor_type = data["type"] || "Person"
+ featured_address = data["featured"]
+ {:ok, pinned_objects} = fetch_and_prepare_featured_from_ap_id(featured_address)
+
public_key =
if is_map(data["publicKey"]) && is_binary(data["publicKey"]["publicKeyPem"]) do
data["publicKey"]["publicKeyPem"]
@@ -1308,23 +1450,25 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do
ap_id: data["id"],
uri: get_actor_url(data["url"]),
ap_enabled: true,
- banner: banner,
+ banner: normalize_image(data["image"]),
fields: fields,
emoji: emojis,
is_locked: is_locked,
is_discoverable: is_discoverable,
invisible: invisible,
- avatar: avatar,
+ avatar: normalize_image(data["icon"]),
name: data["name"],
follower_address: data["followers"],
following_address: data["following"],
+ featured_address: featured_address,
bio: data["summary"] || "",
actor_type: actor_type,
also_known_as: Map.get(data, "alsoKnownAs", []),
public_key: public_key,
inbox: data["inbox"],
shared_inbox: shared_inbox,
- accepts_chat_messages: accepts_chat_messages
+ accepts_chat_messages: accepts_chat_messages,
+ pinned_objects: pinned_objects
}
# nickname can be nil because of virtual actors
@@ -1462,6 +1606,41 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do
end
end
+ def pin_data_from_featured_collection(%{
+ "type" => type,
+ "orderedItems" => objects
+ })
+ when type in ["OrderedCollection", "Collection"] do
+ Map.new(objects, fn %{"id" => object_ap_id} -> {object_ap_id, NaiveDateTime.utc_now()} end)
+ end
+
+ def fetch_and_prepare_featured_from_ap_id(nil) do
+ {:ok, %{}}
+ end
+
+ def fetch_and_prepare_featured_from_ap_id(ap_id) do
+ with {:ok, data} <- Fetcher.fetch_and_contain_remote_object_from_id(ap_id) do
+ {:ok, pin_data_from_featured_collection(data)}
+ else
+ e ->
+ Logger.error("Could not decode featured collection at fetch #{ap_id}, #{inspect(e)}")
+ {:ok, %{}}
+ end
+ end
+
+ def pinned_fetch_task(nil), do: nil
+
+ def pinned_fetch_task(%{pinned_objects: pins}) do
+ if Enum.all?(pins, fn {ap_id, _} ->
+ Object.get_cached_by_ap_id(ap_id) ||
+ match?({:ok, _object}, Fetcher.fetch_object_from_id(ap_id))
+ end) do
+ :ok
+ else
+ :error
+ end
+ end
+
def make_user_from_ap_id(ap_id) do
user = User.get_cached_by_ap_id(ap_id)
@@ -1469,6 +1648,8 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do
Transmogrifier.upgrade_user_from_ap_id(ap_id)
else
with {:ok, data} <- fetch_and_prepare_user_from_ap_id(ap_id) do
+ {:ok, _pid} = Task.start(fn -> pinned_fetch_task(data) end)
+
if user do
user
|> User.remote_user_changeset(data)
diff --git a/lib/pleroma/web/activity_pub/activity_pub_controller.ex b/lib/pleroma/web/activity_pub/activity_pub_controller.ex
index 9d3dcc7f9..5aa3b281a 100644
--- a/lib/pleroma/web/activity_pub/activity_pub_controller.ex
+++ b/lib/pleroma/web/activity_pub/activity_pub_controller.ex
@@ -543,4 +543,12 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubController do
|> json(object.data)
end
end
+
+ def pinned(conn, %{"nickname" => nickname}) do
+ with %User{} = user <- User.get_cached_by_nickname(nickname) do
+ conn
+ |> put_resp_header("content-type", "application/activity+json")
+ |> json(UserView.render("featured.json", %{user: user}))
+ end
+ end
end
diff --git a/lib/pleroma/web/activity_pub/builder.ex b/lib/pleroma/web/activity_pub/builder.ex
index f56bfc600..cde477710 100644
--- a/lib/pleroma/web/activity_pub/builder.ex
+++ b/lib/pleroma/web/activity_pub/builder.ex
@@ -223,7 +223,7 @@ defmodule Pleroma.Web.ActivityPub.Builder do
[actor.follower_address]
public? and Visibility.is_local_public?(object) ->
- [actor.follower_address, object.data["actor"], Pleroma.Constants.as_local_public()]
+ [actor.follower_address, object.data["actor"], Utils.as_local_public()]
public? ->
[actor.follower_address, object.data["actor"], Pleroma.Constants.as_public()]
@@ -273,4 +273,36 @@ defmodule Pleroma.Web.ActivityPub.Builder do
"context" => object.data["context"]
}, []}
end
+
+ @spec pin(User.t(), Object.t()) :: {:ok, map(), keyword()}
+ def pin(%User{} = user, object) do
+ {:ok,
+ %{
+ "id" => Utils.generate_activity_id(),
+ "target" => pinned_url(user.nickname),
+ "object" => object.data["id"],
+ "actor" => user.ap_id,
+ "type" => "Add",
+ "to" => [Pleroma.Constants.as_public()],
+ "cc" => [user.follower_address]
+ }, []}
+ end
+
+ @spec unpin(User.t(), Object.t()) :: {:ok, map, keyword()}
+ def unpin(%User{} = user, object) do
+ {:ok,
+ %{
+ "id" => Utils.generate_activity_id(),
+ "target" => pinned_url(user.nickname),
+ "object" => object.data["id"],
+ "actor" => user.ap_id,
+ "type" => "Remove",
+ "to" => [Pleroma.Constants.as_public()],
+ "cc" => [user.follower_address]
+ }, []}
+ end
+
+ defp pinned_url(nickname) when is_binary(nickname) do
+ Pleroma.Web.Router.Helpers.activity_pub_url(Pleroma.Web.Endpoint, :pinned, nickname)
+ end
end
diff --git a/lib/pleroma/web/activity_pub/mrf.ex b/lib/pleroma/web/activity_pub/mrf.ex
index ef5a09a93..f2fec3ff6 100644
--- a/lib/pleroma/web/activity_pub/mrf.ex
+++ b/lib/pleroma/web/activity_pub/mrf.ex
@@ -92,7 +92,9 @@ defmodule Pleroma.Web.ActivityPub.MRF do
end
def get_policies do
- Pleroma.Config.get([:mrf, :policies], []) |> get_policies()
+ Pleroma.Config.get([:mrf, :policies], [])
+ |> get_policies()
+ |> Enum.concat([Pleroma.Web.ActivityPub.MRF.HashtagPolicy])
end
defp get_policies(policy) when is_atom(policy), do: [policy]
diff --git a/lib/pleroma/web/activity_pub/mrf/follow_bot_policy.ex b/lib/pleroma/web/activity_pub/mrf/follow_bot_policy.ex
new file mode 100644
index 000000000..7307c9c14
--- /dev/null
+++ b/lib/pleroma/web/activity_pub/mrf/follow_bot_policy.ex
@@ -0,0 +1,59 @@
+defmodule Pleroma.Web.ActivityPub.MRF.FollowBotPolicy do
+ @behaviour Pleroma.Web.ActivityPub.MRF
+ alias Pleroma.Config
+ alias Pleroma.User
+ alias Pleroma.Web.CommonAPI
+
+ require Logger
+
+ @impl true
+ def filter(message) do
+ with follower_nickname <- Config.get([:mrf_follow_bot, :follower_nickname]),
+ %User{actor_type: "Service"} = follower <-
+ User.get_cached_by_nickname(follower_nickname),
+ %{"type" => "Create", "object" => %{"type" => "Note"}} <- message do
+ try_follow(follower, message)
+ else
+ nil ->
+ Logger.warn(
+ "#{__MODULE__} skipped because of missing `:mrf_follow_bot, :follower_nickname` configuration, the :follower_nickname
+ account does not exist, or the account is not correctly configured as a bot."
+ )
+
+ {:ok, message}
+
+ _ ->
+ {:ok, message}
+ end
+ end
+
+ defp try_follow(follower, message) do
+ to = Map.get(message, "to", [])
+ cc = Map.get(message, "cc", [])
+ actor = [message["actor"]]
+
+ Enum.concat([to, cc, actor])
+ |> List.flatten()
+ |> Enum.uniq()
+ |> User.get_all_by_ap_id()
+ |> Enum.each(fn user ->
+ with false <- user.local,
+ false <- User.following?(follower, user),
+ false <- User.locked?(user),
+ false <- (user.bio || "") |> String.downcase() |> String.contains?("nobot") do
+ Logger.debug(
+ "#{__MODULE__}: Follow request from #{follower.nickname} to #{user.nickname}"
+ )
+
+ CommonAPI.follow(follower, user)
+ end
+ end)
+
+ {:ok, message}
+ end
+
+ @impl true
+ def describe do
+ {:ok, %{}}
+ end
+end
diff --git a/lib/pleroma/web/activity_pub/mrf/hashtag_policy.ex b/lib/pleroma/web/activity_pub/mrf/hashtag_policy.ex
new file mode 100644
index 000000000..def0c437c
--- /dev/null
+++ b/lib/pleroma/web/activity_pub/mrf/hashtag_policy.ex
@@ -0,0 +1,116 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.Web.ActivityPub.MRF.HashtagPolicy do
+ require Pleroma.Constants
+
+ alias Pleroma.Config
+ alias Pleroma.Object
+
+ @moduledoc """
+ Reject, TWKN-remove or Set-Sensitive messsages with specific hashtags (without the leading #)
+
+ Note: This MRF Policy is always enabled, if you want to disable it you have to set empty lists.
+ """
+
+ @behaviour Pleroma.Web.ActivityPub.MRF
+
+ defp check_reject(message, hashtags) do
+ if Enum.any?(Config.get([:mrf_hashtag, :reject]), fn match -> match in hashtags end) do
+ {:reject, "[HashtagPolicy] Matches with rejected keyword"}
+ else
+ {:ok, message}
+ end
+ end
+
+ defp check_ftl_removal(%{"to" => to} = message, hashtags) do
+ if Pleroma.Constants.as_public() in to and
+ Enum.any?(Config.get([:mrf_hashtag, :federated_timeline_removal]), fn match ->
+ match in hashtags
+ end) do
+ to = List.delete(to, Pleroma.Constants.as_public())
+ cc = [Pleroma.Constants.as_public() | message["cc"] || []]
+
+ message =
+ message
+ |> Map.put("to", to)
+ |> Map.put("cc", cc)
+ |> Kernel.put_in(["object", "to"], to)
+ |> Kernel.put_in(["object", "cc"], cc)
+
+ {:ok, message}
+ else
+ {:ok, message}
+ end
+ end
+
+ defp check_ftl_removal(message, _hashtags), do: {:ok, message}
+
+ defp check_sensitive(message, hashtags) do
+ if Enum.any?(Config.get([:mrf_hashtag, :sensitive]), fn match -> match in hashtags end) do
+ {:ok, Kernel.put_in(message, ["object", "sensitive"], true)}
+ else
+ {:ok, message}
+ end
+ end
+
+ @impl true
+ def filter(%{"type" => "Create", "object" => object} = message) do
+ hashtags = Object.hashtags(%Object{data: object})
+
+ if hashtags != [] do
+ with {:ok, message} <- check_reject(message, hashtags),
+ {:ok, message} <- check_ftl_removal(message, hashtags),
+ {:ok, message} <- check_sensitive(message, hashtags) do
+ {:ok, message}
+ end
+ else
+ {:ok, message}
+ end
+ end
+
+ @impl true
+ def filter(message), do: {:ok, message}
+
+ @impl true
+ def describe do
+ mrf_hashtag =
+ Config.get(:mrf_hashtag)
+ |> Enum.into(%{})
+
+ {:ok, %{mrf_hashtag: mrf_hashtag}}
+ end
+
+ @impl true
+ def config_description do
+ %{
+ key: :mrf_hashtag,
+ related_policy: "Pleroma.Web.ActivityPub.MRF.HashtagPolicy",
+ label: "MRF Hashtag",
+ description: @moduledoc,
+ children: [
+ %{
+ key: :reject,
+ type: {:list, :string},
+ description: "A list of hashtags which result in message being rejected.",
+ suggestions: ["foo"]
+ },
+ %{
+ key: :federated_timeline_removal,
+ type: {:list, :string},
+ description:
+ "A list of hashtags which result in message being removed from federated timelines (a.k.a unlisted).",
+ suggestions: ["foo"]
+ },
+ %{
+ key: :sensitive,
+ type: {:list, :string},
+ description:
+ "A list of hashtags which result in message being set as sensitive (a.k.a NSFW/R-18)",
+ suggestions: ["nsfw", "r18"]
+ }
+ ]
+ }
+ end
+end
diff --git a/lib/pleroma/web/activity_pub/mrf/simple_policy.ex b/lib/pleroma/web/activity_pub/mrf/simple_policy.ex
index bb3838d2c..d40348cb1 100644
--- a/lib/pleroma/web/activity_pub/mrf/simple_policy.ex
+++ b/lib/pleroma/web/activity_pub/mrf/simple_policy.ex
@@ -64,20 +64,16 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicy do
%{host: actor_host} = _actor_info,
%{
"type" => "Create",
- "object" => child_object
+ "object" => %{} = _child_object
} = object
- )
- when is_map(child_object) do
+ ) do
media_nsfw =
Config.get([:mrf_simple, :media_nsfw])
|> MRF.subdomains_regex()
object =
if MRF.subdomain_match?(media_nsfw, actor_host) do
- tags = (child_object["tag"] || []) ++ ["nsfw"]
- child_object = Map.put(child_object, "tag", tags)
- child_object = Map.put(child_object, "sensitive", true)
- Map.put(object, "object", child_object)
+ Kernel.put_in(object, ["object", "sensitive"], true)
else
object
end
@@ -181,6 +177,14 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicy do
defp check_banner_removal(_actor_info, object), do: {:ok, object}
+ defp check_object(%{"object" => object} = activity) do
+ with {:ok, _object} <- filter(object) do
+ {:ok, activity}
+ end
+ end
+
+ defp check_object(object), do: {:ok, object}
+
@impl true
def filter(%{"type" => "Delete", "actor" => actor} = object) do
%{host: actor_host} = URI.parse(actor)
@@ -206,7 +210,8 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicy do
{:ok, object} <- check_media_nsfw(actor_info, object),
{:ok, object} <- check_ftl_removal(actor_info, object),
{:ok, object} <- check_followers_only(actor_info, object),
- {:ok, object} <- check_report_removal(actor_info, object) do
+ {:ok, object} <- check_report_removal(actor_info, object),
+ {:ok, object} <- check_object(object) do
{:ok, object}
else
{:reject, nil} -> {:reject, "[SimplePolicy]"}
@@ -231,6 +236,19 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicy do
end
end
+ def filter(object) when is_binary(object) do
+ uri = URI.parse(object)
+
+ with {:ok, object} <- check_accept(uri, object),
+ {:ok, object} <- check_reject(uri, object) do
+ {:ok, object}
+ else
+ {:reject, nil} -> {:reject, "[SimplePolicy]"}
+ {:reject, _} = e -> e
+ _ -> {:reject, "[SimplePolicy]"}
+ end
+ end
+
def filter(object), do: {:ok, object}
@impl true
diff --git a/lib/pleroma/web/activity_pub/mrf/tag_policy.ex b/lib/pleroma/web/activity_pub/mrf/tag_policy.ex
index 5739cee63..528093ac0 100644
--- a/lib/pleroma/web/activity_pub/mrf/tag_policy.ex
+++ b/lib/pleroma/web/activity_pub/mrf/tag_policy.ex
@@ -28,20 +28,11 @@ defmodule Pleroma.Web.ActivityPub.MRF.TagPolicy do
"mrf_tag:media-force-nsfw",
%{
"type" => "Create",
- "object" => %{"attachment" => child_attachment} = object
+ "object" => %{"attachment" => child_attachment}
} = message
)
when length(child_attachment) > 0 do
- tags = (object["tag"] || []) ++ ["nsfw"]
-
- object =
- object
- |> Map.put("tag", tags)
- |> Map.put("sensitive", true)
-
- message = Map.put(message, "object", object)
-
- {:ok, message}
+ {:ok, Kernel.put_in(message, ["object", "sensitive"], true)}
end
defp process_tag(
diff --git a/lib/pleroma/web/activity_pub/object_validator.ex b/lib/pleroma/web/activity_pub/object_validator.ex
index 297c19cc0..248a12a36 100644
--- a/lib/pleroma/web/activity_pub/object_validator.ex
+++ b/lib/pleroma/web/activity_pub/object_validator.ex
@@ -17,6 +17,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidator do
alias Pleroma.Object.Containment
alias Pleroma.User
alias Pleroma.Web.ActivityPub.ObjectValidators.AcceptRejectValidator
+ alias Pleroma.Web.ActivityPub.ObjectValidators.AddRemoveValidator
alias Pleroma.Web.ActivityPub.ObjectValidators.AnnounceValidator
alias Pleroma.Web.ActivityPub.ObjectValidators.AnswerValidator
alias Pleroma.Web.ActivityPub.ObjectValidators.ArticleNoteValidator
@@ -37,37 +38,6 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidator do
@impl true
def validate(object, meta)
- def validate(%{"type" => type} = object, meta)
- when type in ~w[Accept Reject] do
- with {:ok, object} <-
- object
- |> AcceptRejectValidator.cast_and_validate()
- |> Ecto.Changeset.apply_action(:insert) do
- object = stringify_keys(object)
- {:ok, object, meta}
- end
- end
-
- def validate(%{"type" => "Event"} = object, meta) do
- with {:ok, object} <-
- object
- |> EventValidator.cast_and_validate()
- |> Ecto.Changeset.apply_action(:insert) do
- object = stringify_keys(object)
- {:ok, object, meta}
- end
- end
-
- def validate(%{"type" => "Follow"} = object, meta) do
- with {:ok, object} <-
- object
- |> FollowValidator.cast_and_validate()
- |> Ecto.Changeset.apply_action(:insert) do
- object = stringify_keys(object)
- {:ok, object, meta}
- end
- end
-
def validate(%{"type" => "Block"} = block_activity, meta) do
with {:ok, block_activity} <-
block_activity
@@ -87,16 +57,6 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidator do
end
end
- def validate(%{"type" => "Update"} = update_activity, meta) do
- with {:ok, update_activity} <-
- update_activity
- |> UpdateValidator.cast_and_validate()
- |> Ecto.Changeset.apply_action(:insert) do
- update_activity = stringify_keys(update_activity)
- {:ok, update_activity, meta}
- end
- end
-
def validate(%{"type" => "Undo"} = object, meta) do
with {:ok, object} <-
object
@@ -123,76 +83,6 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidator do
end
end
- def validate(%{"type" => "Like"} = object, meta) do
- with {:ok, object} <-
- object
- |> LikeValidator.cast_and_validate()
- |> Ecto.Changeset.apply_action(:insert) do
- object = stringify_keys(object)
- {:ok, object, meta}
- end
- end
-
- def validate(%{"type" => "ChatMessage"} = object, meta) do
- with {:ok, object} <-
- object
- |> ChatMessageValidator.cast_and_validate()
- |> Ecto.Changeset.apply_action(:insert) do
- object = stringify_keys(object)
- {:ok, object, meta}
- end
- end
-
- def validate(%{"type" => "Question"} = object, meta) do
- with {:ok, object} <-
- object
- |> QuestionValidator.cast_and_validate()
- |> Ecto.Changeset.apply_action(:insert) do
- object = stringify_keys(object)
- {:ok, object, meta}
- end
- end
-
- def validate(%{"type" => type} = object, meta) when type in ~w[Audio Video] do
- with {:ok, object} <-
- object
- |> AudioVideoValidator.cast_and_validate()
- |> Ecto.Changeset.apply_action(:insert) do
- object = stringify_keys(object)
- {:ok, object, meta}
- end
- end
-
- def validate(%{"type" => "Article"} = object, meta) do
- with {:ok, object} <-
- object
- |> ArticleNoteValidator.cast_and_validate()
- |> Ecto.Changeset.apply_action(:insert) do
- object = stringify_keys(object)
- {:ok, object, meta}
- end
- end
-
- def validate(%{"type" => "Answer"} = object, meta) do
- with {:ok, object} <-
- object
- |> AnswerValidator.cast_and_validate()
- |> Ecto.Changeset.apply_action(:insert) do
- object = stringify_keys(object)
- {:ok, object, meta}
- end
- end
-
- def validate(%{"type" => "EmojiReact"} = object, meta) do
- with {:ok, object} <-
- object
- |> EmojiReactValidator.cast_and_validate()
- |> Ecto.Changeset.apply_action(:insert) do
- object = stringify_keys(object)
- {:ok, object, meta}
- end
- end
-
def validate(
%{"type" => "Create", "object" => %{"type" => "ChatMessage"} = object} = create_activity,
meta
@@ -212,7 +102,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidator do
%{"type" => "Create", "object" => %{"type" => objtype} = object} = create_activity,
meta
)
- when objtype in ~w[Question Answer Audio Video Event Article] do
+ when objtype in ~w[Question Answer Audio Video Event Article Note] do
with {:ok, object_data} <- cast_and_apply(object),
meta = Keyword.put(meta, :object_data, object_data |> stringify_keys),
{:ok, create_activity} <-
@@ -224,10 +114,61 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidator do
end
end
- def validate(%{"type" => "Announce"} = object, meta) do
+ def validate(%{"type" => type} = object, meta)
+ when type in ~w[Event Question Audio Video Article Note] do
+ validator =
+ case type do
+ "Event" -> EventValidator
+ "Question" -> QuestionValidator
+ "Audio" -> AudioVideoValidator
+ "Video" -> AudioVideoValidator
+ "Article" -> ArticleNoteValidator
+ "Note" -> ArticleNoteValidator
+ end
+
+ with {:ok, object} <-
+ object
+ |> validator.cast_and_validate()
+ |> Ecto.Changeset.apply_action(:insert) do
+ object = stringify_keys(object)
+
+ # Insert copy of hashtags as strings for the non-hashtag table indexing
+ tag = (object["tag"] || []) ++ Object.hashtags(%Object{data: object})
+ object = Map.put(object, "tag", tag)
+
+ {:ok, object, meta}
+ end
+ end
+
+ def validate(%{"type" => type} = object, meta)
+ when type in ~w[Accept Reject Follow Update Like EmojiReact Announce
+ ChatMessage Answer] do
+ validator =
+ case type do
+ "Accept" -> AcceptRejectValidator
+ "Reject" -> AcceptRejectValidator
+ "Follow" -> FollowValidator
+ "Update" -> UpdateValidator
+ "Like" -> LikeValidator
+ "EmojiReact" -> EmojiReactValidator
+ "Announce" -> AnnounceValidator
+ "ChatMessage" -> ChatMessageValidator
+ "Answer" -> AnswerValidator
+ end
+
+ with {:ok, object} <-
+ object
+ |> validator.cast_and_validate()
+ |> Ecto.Changeset.apply_action(:insert) do
+ object = stringify_keys(object)
+ {:ok, object, meta}
+ end
+ end
+
+ def validate(%{"type" => type} = object, meta) when type in ~w(Add Remove) do
with {:ok, object} <-
object
- |> AnnounceValidator.cast_and_validate()
+ |> AddRemoveValidator.cast_and_validate()
|> Ecto.Changeset.apply_action(:insert) do
object = stringify_keys(object)
{:ok, object, meta}
@@ -254,13 +195,13 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidator do
EventValidator.cast_and_apply(object)
end
- def cast_and_apply(%{"type" => "Article"} = object) do
+ def cast_and_apply(%{"type" => type} = object) when type in ~w[Article Note] do
ArticleNoteValidator.cast_and_apply(object)
end
def cast_and_apply(o), do: {:error, {:validator_not_set, o}}
- # is_struct/1 isn't present in Elixir 1.8.x
+ # is_struct/1 appears in Elixir 1.11
def stringify_keys(%{__struct__: _} = object) do
object
|> Map.from_struct()
diff --git a/lib/pleroma/web/activity_pub/object_validators/accept_reject_validator.ex b/lib/pleroma/web/activity_pub/object_validators/accept_reject_validator.ex
index d31e780c3..b577a1044 100644
--- a/lib/pleroma/web/activity_pub/object_validators/accept_reject_validator.ex
+++ b/lib/pleroma/web/activity_pub/object_validators/accept_reject_validator.ex
@@ -27,7 +27,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.AcceptRejectValidator do
|> cast(data, __schema__(:fields))
end
- def validate_data(cng) do
+ defp validate_data(cng) do
cng
|> validate_required([:id, :type, :actor, :to, :cc, :object])
|> validate_inclusion(:type, ["Accept", "Reject"])
diff --git a/lib/pleroma/web/activity_pub/object_validators/add_remove_validator.ex b/lib/pleroma/web/activity_pub/object_validators/add_remove_validator.ex
new file mode 100644
index 000000000..f885aabe4
--- /dev/null
+++ b/lib/pleroma/web/activity_pub/object_validators/add_remove_validator.ex
@@ -0,0 +1,77 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.Web.ActivityPub.ObjectValidators.AddRemoveValidator do
+ use Ecto.Schema
+
+ import Ecto.Changeset
+ import Pleroma.Web.ActivityPub.ObjectValidators.CommonValidations
+
+ require Pleroma.Constants
+
+ alias Pleroma.EctoType.ActivityPub.ObjectValidators
+ alias Pleroma.User
+
+ @primary_key false
+
+ embedded_schema do
+ field(:id, ObjectValidators.ObjectID, primary_key: true)
+ field(:target)
+ field(:object, ObjectValidators.ObjectID)
+ field(:actor, ObjectValidators.ObjectID)
+ field(:type)
+ field(:to, ObjectValidators.Recipients, default: [])
+ field(:cc, ObjectValidators.Recipients, default: [])
+ end
+
+ def cast_and_validate(data) do
+ {:ok, actor} = User.get_or_fetch_by_ap_id(data["actor"])
+
+ {:ok, actor} = maybe_refetch_user(actor)
+
+ data
+ |> maybe_fix_data_for_mastodon(actor)
+ |> cast_data()
+ |> validate_data(actor)
+ end
+
+ defp maybe_fix_data_for_mastodon(data, actor) do
+ # Mastodon sends pin/unpin objects without id, to, cc fields
+ data
+ |> Map.put_new("id", Pleroma.Web.ActivityPub.Utils.generate_activity_id())
+ |> Map.put_new("to", [Pleroma.Constants.as_public()])
+ |> Map.put_new("cc", [actor.follower_address])
+ end
+
+ defp cast_data(data) do
+ cast(%__MODULE__{}, data, __schema__(:fields))
+ end
+
+ defp validate_data(changeset, actor) do
+ changeset
+ |> validate_required([:id, :target, :object, :actor, :type, :to, :cc])
+ |> validate_inclusion(:type, ~w(Add Remove))
+ |> validate_actor_presence()
+ |> validate_collection_belongs_to_actor(actor)
+ |> validate_object_presence()
+ end
+
+ defp validate_collection_belongs_to_actor(changeset, actor) do
+ validate_change(changeset, :target, fn :target, target ->
+ if target == actor.featured_address do
+ []
+ else
+ [target: "collection doesn't belong to actor"]
+ end
+ end)
+ end
+
+ defp maybe_refetch_user(%User{featured_address: address} = user) when is_binary(address) do
+ {:ok, user}
+ end
+
+ defp maybe_refetch_user(%User{ap_id: ap_id}) do
+ Pleroma.Web.ActivityPub.Transmogrifier.upgrade_user_from_ap_id(ap_id)
+ end
+end
diff --git a/lib/pleroma/web/activity_pub/object_validators/announce_validator.ex b/lib/pleroma/web/activity_pub/object_validators/announce_validator.ex
index b08a33e68..a2f752ac3 100644
--- a/lib/pleroma/web/activity_pub/object_validators/announce_validator.ex
+++ b/lib/pleroma/web/activity_pub/object_validators/announce_validator.ex
@@ -50,7 +50,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.AnnounceValidator do
cng
end
- def validate_data(data_cng) do
+ defp validate_data(data_cng) do
data_cng
|> validate_inclusion(:type, ["Announce"])
|> validate_required([:id, :type, :object, :actor, :to, :cc])
@@ -68,7 +68,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.AnnounceValidator do
false <- Visibility.is_public?(object) do
same_actor = object.data["actor"] == actor.ap_id
recipients = get_field(cng, :to) ++ get_field(cng, :cc)
- local_public = Pleroma.Constants.as_local_public()
+ local_public = Utils.as_local_public()
is_public =
Enum.member?(recipients, Pleroma.Constants.as_public()) or
diff --git a/lib/pleroma/web/activity_pub/object_validators/answer_validator.ex b/lib/pleroma/web/activity_pub/object_validators/answer_validator.ex
index 15e4413cd..3451e1ff8 100644
--- a/lib/pleroma/web/activity_pub/object_validators/answer_validator.ex
+++ b/lib/pleroma/web/activity_pub/object_validators/answer_validator.ex
@@ -6,6 +6,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.AnswerValidator do
use Ecto.Schema
alias Pleroma.EctoType.ActivityPub.ObjectValidators
+ alias Pleroma.Web.ActivityPub.ObjectValidators.CommonFixes
alias Pleroma.Web.ActivityPub.ObjectValidators.CommonValidations
import Ecto.Changeset
@@ -23,6 +24,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.AnswerValidator do
field(:name, :string)
field(:inReplyTo, ObjectValidators.ObjectID)
field(:attributedTo, ObjectValidators.ObjectID)
+ field(:context, :string)
# TODO: Remove actor on objects
field(:actor, ObjectValidators.ObjectID)
@@ -46,11 +48,16 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.AnswerValidator do
end
def changeset(struct, data) do
+ data =
+ data
+ |> CommonFixes.fix_actor()
+ |> CommonFixes.fix_object_defaults()
+
struct
|> cast(data, __schema__(:fields))
end
- def validate_data(data_cng) do
+ defp validate_data(data_cng) do
data_cng
|> validate_inclusion(:type, ["Answer"])
|> validate_required([:id, :inReplyTo, :name, :attributedTo, :actor])
diff --git a/lib/pleroma/web/activity_pub/object_validators/article_note_validator.ex b/lib/pleroma/web/activity_pub/object_validators/article_note_validator.ex
index b0388ef3b..193f85f49 100644
--- a/lib/pleroma/web/activity_pub/object_validators/article_note_validator.ex
+++ b/lib/pleroma/web/activity_pub/object_validators/article_note_validator.ex
@@ -9,6 +9,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.ArticleNoteValidator do
alias Pleroma.Web.ActivityPub.ObjectValidators.AttachmentValidator
alias Pleroma.Web.ActivityPub.ObjectValidators.CommonFixes
alias Pleroma.Web.ActivityPub.ObjectValidators.CommonValidations
+ alias Pleroma.Web.ActivityPub.ObjectValidators.TagValidator
alias Pleroma.Web.ActivityPub.Transmogrifier
import Ecto.Changeset
@@ -22,8 +23,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.ArticleNoteValidator do
field(:cc, ObjectValidators.Recipients, default: [])
field(:bto, ObjectValidators.Recipients, default: [])
field(:bcc, ObjectValidators.Recipients, default: [])
- # TODO: Write type
- field(:tag, {:array, :map}, default: [])
+ embeds_many(:tag, TagValidator)
field(:type, :string)
field(:name, :string)
@@ -50,6 +50,8 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.ArticleNoteValidator do
field(:likes, {:array, ObjectValidators.ObjectID}, default: [])
field(:announcements, {:array, ObjectValidators.ObjectID}, default: [])
+
+ field(:replies, {:array, ObjectValidators.ObjectID}, default: [])
end
def cast_and_apply(data) do
@@ -65,36 +67,51 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.ArticleNoteValidator do
end
def cast_data(data) do
- data = fix(data)
-
%__MODULE__{}
|> changeset(data)
end
- defp fix_url(%{"url" => url} = data) when is_map(url) do
- Map.put(data, "url", url["href"])
- end
-
+ defp fix_url(%{"url" => url} = data) when is_bitstring(url), do: data
+ defp fix_url(%{"url" => url} = data) when is_map(url), do: Map.put(data, "url", url["href"])
defp fix_url(data), do: data
+ defp fix_tag(%{"tag" => tag} = data) when is_list(tag), do: data
+ defp fix_tag(%{"tag" => tag} = data) when is_map(tag), do: Map.put(data, "tag", [tag])
+ defp fix_tag(data), do: Map.drop(data, ["tag"])
+
+ defp fix_replies(%{"replies" => %{"first" => %{"items" => replies}}} = data)
+ when is_list(replies),
+ do: Map.put(data, "replies", replies)
+
+ defp fix_replies(%{"replies" => %{"items" => replies}} = data) when is_list(replies),
+ do: Map.put(data, "replies", replies)
+
+ defp fix_replies(%{"replies" => replies} = data) when is_bitstring(replies),
+ do: Map.drop(data, ["replies"])
+
+ defp fix_replies(data), do: data
+
defp fix(data) do
data
- |> CommonFixes.fix_defaults()
- |> CommonFixes.fix_attribution()
|> CommonFixes.fix_actor()
+ |> CommonFixes.fix_object_defaults()
|> fix_url()
+ |> fix_tag()
+ |> fix_replies()
|> Transmogrifier.fix_emoji()
+ |> Transmogrifier.fix_content_map()
end
def changeset(struct, data) do
data = fix(data)
struct
- |> cast(data, __schema__(:fields) -- [:attachment])
+ |> cast(data, __schema__(:fields) -- [:attachment, :tag])
|> cast_embed(:attachment)
+ |> cast_embed(:tag)
end
- def validate_data(data_cng) do
+ defp validate_data(data_cng) do
data_cng
|> validate_inclusion(:type, ["Article", "Note"])
|> validate_required([:id, :actor, :attributedTo, :type, :context, :context_id])
diff --git a/lib/pleroma/web/activity_pub/object_validators/attachment_validator.ex b/lib/pleroma/web/activity_pub/object_validators/attachment_validator.ex
index 3175427ad..bba2f5eb0 100644
--- a/lib/pleroma/web/activity_pub/object_validators/attachment_validator.ex
+++ b/lib/pleroma/web/activity_pub/object_validators/attachment_validator.ex
@@ -6,7 +6,6 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.AttachmentValidator do
use Ecto.Schema
alias Pleroma.EctoType.ActivityPub.ObjectValidators
- alias Pleroma.Web.ActivityPub.ObjectValidators.UrlObjectValidator
import Ecto.Changeset
@@ -21,6 +20,8 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.AttachmentValidator do
field(:type, :string)
field(:href, ObjectValidators.Uri)
field(:mediaType, :string, default: "application/octet-stream")
+ field(:width, :integer)
+ field(:height, :integer)
end
end
@@ -52,7 +53,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.AttachmentValidator do
data = fix_media_type(data)
struct
- |> cast(data, [:type, :href, :mediaType])
+ |> cast(data, [:type, :href, :mediaType, :width, :height])
|> validate_inclusion(:type, ["Link"])
|> validate_required([:type, :href, :mediaType])
end
@@ -90,7 +91,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.AttachmentValidator do
end
end
- def validate_data(cng) do
+ defp validate_data(cng) do
cng
|> validate_inclusion(:type, ~w[Document Audio Image Video])
|> validate_required([:mediaType, :url, :type])
diff --git a/lib/pleroma/web/activity_pub/object_validators/audio_video_validator.ex b/lib/pleroma/web/activity_pub/object_validators/audio_video_validator.ex
index 4a96fef52..572687deb 100644
--- a/lib/pleroma/web/activity_pub/object_validators/audio_video_validator.ex
+++ b/lib/pleroma/web/activity_pub/object_validators/audio_video_validator.ex
@@ -5,11 +5,11 @@
defmodule Pleroma.Web.ActivityPub.ObjectValidators.AudioVideoValidator do
use Ecto.Schema
- alias Pleroma.EarmarkRenderer
alias Pleroma.EctoType.ActivityPub.ObjectValidators
alias Pleroma.Web.ActivityPub.ObjectValidators.AttachmentValidator
alias Pleroma.Web.ActivityPub.ObjectValidators.CommonFixes
alias Pleroma.Web.ActivityPub.ObjectValidators.CommonValidations
+ alias Pleroma.Web.ActivityPub.ObjectValidators.TagValidator
alias Pleroma.Web.ActivityPub.Transmogrifier
import Ecto.Changeset
@@ -23,8 +23,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.AudioVideoValidator do
field(:cc, ObjectValidators.Recipients, default: [])
field(:bto, ObjectValidators.Recipients, default: [])
field(:bcc, ObjectValidators.Recipients, default: [])
- # TODO: Write type
- field(:tag, {:array, :map}, default: [])
+ embeds_many(:tag, TagValidator)
field(:type, :string)
field(:name, :string)
@@ -110,7 +109,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.AudioVideoValidator do
when is_binary(content) do
content =
content
- |> Earmark.as_html!(%Earmark.Options{renderer: EarmarkRenderer})
+ |> Pleroma.Formatter.markdown_to_html()
|> Pleroma.HTML.filter_tags()
Map.put(data, "content", content)
@@ -120,9 +119,8 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.AudioVideoValidator do
defp fix(data) do
data
- |> CommonFixes.fix_defaults()
- |> CommonFixes.fix_attribution()
|> CommonFixes.fix_actor()
+ |> CommonFixes.fix_object_defaults()
|> Transmogrifier.fix_emoji()
|> fix_url()
|> fix_content()
@@ -132,11 +130,12 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.AudioVideoValidator do
data = fix(data)
struct
- |> cast(data, __schema__(:fields) -- [:attachment])
+ |> cast(data, __schema__(:fields) -- [:attachment, :tag])
|> cast_embed(:attachment)
+ |> cast_embed(:tag)
end
- def validate_data(data_cng) do
+ defp validate_data(data_cng) do
data_cng
|> validate_inclusion(:type, ["Audio", "Video"])
|> validate_required([:id, :actor, :attributedTo, :type, :context, :attachment])
diff --git a/lib/pleroma/web/activity_pub/object_validators/block_validator.ex b/lib/pleroma/web/activity_pub/object_validators/block_validator.ex
index c5f77bb76..88948135f 100644
--- a/lib/pleroma/web/activity_pub/object_validators/block_validator.ex
+++ b/lib/pleroma/web/activity_pub/object_validators/block_validator.ex
@@ -26,7 +26,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.BlockValidator do
|> cast(data, __schema__(:fields))
end
- def validate_data(cng) do
+ defp validate_data(cng) do
cng
|> validate_required([:id, :type, :actor, :to, :cc, :object])
|> validate_inclusion(:type, ["Block"])
diff --git a/lib/pleroma/web/activity_pub/object_validators/chat_message_validator.ex b/lib/pleroma/web/activity_pub/object_validators/chat_message_validator.ex
index 1189778f2..b153156b0 100644
--- a/lib/pleroma/web/activity_pub/object_validators/chat_message_validator.ex
+++ b/lib/pleroma/web/activity_pub/object_validators/chat_message_validator.ex
@@ -67,7 +67,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.ChatMessageValidator do
|> cast_embed(:attachment)
end
- def validate_data(data_cng) do
+ defp validate_data(data_cng) do
data_cng
|> validate_inclusion(:type, ["ChatMessage"])
|> validate_required([:id, :actor, :to, :type, :published])
diff --git a/lib/pleroma/web/activity_pub/object_validators/common_fixes.ex b/lib/pleroma/web/activity_pub/object_validators/common_fixes.ex
index 5f2c633bc..c958fcc5d 100644
--- a/lib/pleroma/web/activity_pub/object_validators/common_fixes.ex
+++ b/lib/pleroma/web/activity_pub/object_validators/common_fixes.ex
@@ -3,26 +3,55 @@
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.ActivityPub.ObjectValidators.CommonFixes do
+ alias Pleroma.EctoType.ActivityPub.ObjectValidators
alias Pleroma.Object.Containment
+ alias Pleroma.User
+ alias Pleroma.Web.ActivityPub.Transmogrifier
alias Pleroma.Web.ActivityPub.Utils
- # based on Pleroma.Web.ActivityPub.Utils.lazy_put_objects_defaults
- def fix_defaults(data) do
+ def cast_and_filter_recipients(message, field, follower_collection, field_fallback \\ []) do
+ {:ok, data} = ObjectValidators.Recipients.cast(message[field] || field_fallback)
+
+ data =
+ Enum.reject(data, fn x ->
+ String.ends_with?(x, "/followers") and x != follower_collection
+ end)
+
+ Map.put(message, field, data)
+ end
+
+ def fix_object_defaults(data) do
%{data: %{"id" => context}, id: context_id} =
Utils.create_context(data["context"] || data["conversation"])
+ %User{follower_address: follower_collection} = User.get_cached_by_ap_id(data["attributedTo"])
+
data
|> Map.put("context", context)
|> Map.put("context_id", context_id)
+ |> cast_and_filter_recipients("to", follower_collection)
+ |> cast_and_filter_recipients("cc", follower_collection)
+ |> cast_and_filter_recipients("bto", follower_collection)
+ |> cast_and_filter_recipients("bcc", follower_collection)
+ |> Transmogrifier.fix_implicit_addressing(follower_collection)
end
- def fix_attribution(data) do
- data
- |> Map.put_new("actor", data["attributedTo"])
+ def fix_activity_addressing(activity, _meta) do
+ %User{follower_address: follower_collection} = User.get_cached_by_ap_id(activity["actor"])
+
+ activity
+ |> cast_and_filter_recipients("to", follower_collection)
+ |> cast_and_filter_recipients("cc", follower_collection)
+ |> cast_and_filter_recipients("bto", follower_collection)
+ |> cast_and_filter_recipients("bcc", follower_collection)
+ |> Transmogrifier.fix_implicit_addressing(follower_collection)
end
def fix_actor(data) do
- actor = Containment.get_actor(data)
+ actor =
+ data
+ |> Map.put_new("actor", data["attributedTo"])
+ |> Containment.get_actor()
data
|> Map.put("actor", actor)
diff --git a/lib/pleroma/web/activity_pub/object_validators/common_validations.ex b/lib/pleroma/web/activity_pub/object_validators/common_validations.ex
index 093549a45..be5074348 100644
--- a/lib/pleroma/web/activity_pub/object_validators/common_validations.ex
+++ b/lib/pleroma/web/activity_pub/object_validators/common_validations.ex
@@ -9,11 +9,13 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.CommonValidations do
alias Pleroma.Object
alias Pleroma.User
+ @spec validate_any_presence(Ecto.Changeset.t(), [atom()]) :: Ecto.Changeset.t()
def validate_any_presence(cng, fields) do
non_empty =
fields
|> Enum.map(fn field -> get_field(cng, field) end)
|> Enum.any?(fn
+ nil -> false
[] -> false
_ -> true
end)
@@ -29,6 +31,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.CommonValidations do
end
end
+ @spec validate_actor_presence(Ecto.Changeset.t(), keyword()) :: Ecto.Changeset.t()
def validate_actor_presence(cng, options \\ []) do
field_name = Keyword.get(options, :field_name, :actor)
@@ -47,6 +50,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.CommonValidations do
end)
end
+ @spec validate_object_presence(Ecto.Changeset.t(), keyword()) :: Ecto.Changeset.t()
def validate_object_presence(cng, options \\ []) do
field_name = Keyword.get(options, :field_name, :object)
allowed_types = Keyword.get(options, :allowed_types, false)
@@ -68,6 +72,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.CommonValidations do
end)
end
+ @spec validate_object_or_user_presence(Ecto.Changeset.t(), keyword()) :: Ecto.Changeset.t()
def validate_object_or_user_presence(cng, options \\ []) do
field_name = Keyword.get(options, :field_name, :object)
options = Keyword.put(options, :field_name, field_name)
@@ -83,6 +88,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.CommonValidations do
if actor_cng.valid?, do: actor_cng, else: object_cng
end
+ @spec validate_host_match(Ecto.Changeset.t(), [atom()]) :: Ecto.Changeset.t()
def validate_host_match(cng, fields \\ [:id, :actor]) do
if same_domain?(cng, fields) do
cng
@@ -95,6 +101,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.CommonValidations do
end
end
+ @spec validate_fields_match(Ecto.Changeset.t(), [atom()]) :: Ecto.Changeset.t()
def validate_fields_match(cng, fields) do
if map_unique?(cng, fields) do
cng
@@ -122,12 +129,14 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.CommonValidations do
end)
end
+ @spec same_domain?(Ecto.Changeset.t(), [atom()]) :: boolean()
def same_domain?(cng, fields \\ [:actor, :object]) do
map_unique?(cng, fields, fn value -> URI.parse(value).host end)
end
# This figures out if a user is able to create, delete or modify something
# based on the domain and superuser status
+ @spec validate_modification_rights(Ecto.Changeset.t()) :: Ecto.Changeset.t()
def validate_modification_rights(cng) do
actor = User.get_cached_by_ap_id(get_field(cng, :actor))
diff --git a/lib/pleroma/web/activity_pub/object_validators/create_chat_message_validator.ex b/lib/pleroma/web/activity_pub/object_validators/create_chat_message_validator.ex
index 8384c16a7..7a31a99bf 100644
--- a/lib/pleroma/web/activity_pub/object_validators/create_chat_message_validator.ex
+++ b/lib/pleroma/web/activity_pub/object_validators/create_chat_message_validator.ex
@@ -39,7 +39,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.CreateChatMessageValidator do
|> validate_data(meta)
end
- def validate_data(cng, meta \\ []) do
+ defp validate_data(cng, meta) do
cng
|> validate_required([:id, :actor, :to, :type, :object])
|> validate_inclusion(:type, ["Create"])
diff --git a/lib/pleroma/web/activity_pub/object_validators/create_generic_validator.ex b/lib/pleroma/web/activity_pub/object_validators/create_generic_validator.ex
index bf56a918c..d2de53049 100644
--- a/lib/pleroma/web/activity_pub/object_validators/create_generic_validator.ex
+++ b/lib/pleroma/web/activity_pub/object_validators/create_generic_validator.ex
@@ -10,8 +10,10 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.CreateGenericValidator do
alias Pleroma.EctoType.ActivityPub.ObjectValidators
alias Pleroma.Object
+ alias Pleroma.User
alias Pleroma.Web.ActivityPub.ObjectValidators.CommonFixes
alias Pleroma.Web.ActivityPub.ObjectValidators.CommonValidations
+ alias Pleroma.Web.ActivityPub.Transmogrifier
import Ecto.Changeset
@@ -23,6 +25,8 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.CreateGenericValidator do
field(:type, :string)
field(:to, ObjectValidators.Recipients, default: [])
field(:cc, ObjectValidators.Recipients, default: [])
+ field(:bto, ObjectValidators.Recipients, default: [])
+ field(:bcc, ObjectValidators.Recipients, default: [])
field(:object, ObjectValidators.ObjectID)
field(:expires_at, ObjectValidators.DateTime)
@@ -54,39 +58,37 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.CreateGenericValidator do
|> cast(data, __schema__(:fields))
end
- defp fix_context(data, meta) do
- if object = meta[:object_data] do
- Map.put_new(data, "context", object["context"])
- else
- data
- end
- end
+ # CommonFixes.fix_activity_addressing adapted for Create specific behavior
+ defp fix_addressing(data, object) do
+ %User{follower_address: follower_collection} = User.get_cached_by_ap_id(data["actor"])
- defp fix_addressing(data, meta) do
- if object = meta[:object_data] do
- data
- |> Map.put_new("to", object["to"] || [])
- |> Map.put_new("cc", object["cc"] || [])
- else
- data
- end
+ data
+ |> CommonFixes.cast_and_filter_recipients("to", follower_collection, object["to"])
+ |> CommonFixes.cast_and_filter_recipients("cc", follower_collection, object["cc"])
+ |> CommonFixes.cast_and_filter_recipients("bto", follower_collection, object["bto"])
+ |> CommonFixes.cast_and_filter_recipients("bcc", follower_collection, object["bcc"])
+ |> Transmogrifier.fix_implicit_addressing(follower_collection)
end
- defp fix(data, meta) do
+ def fix(data, meta) do
+ object = meta[:object_data]
+
data
- |> fix_context(meta)
- |> fix_addressing(meta)
|> CommonFixes.fix_actor()
+ |> Map.put_new("context", object["context"])
+ |> fix_addressing(object)
end
- def validate_data(cng, meta \\ []) do
+ defp validate_data(cng, meta) do
+ object = meta[:object_data]
+
cng
- |> validate_required([:actor, :type, :object])
+ |> validate_required([:actor, :type, :object, :to, :cc])
|> validate_inclusion(:type, ["Create"])
|> CommonValidations.validate_actor_presence()
- |> CommonValidations.validate_any_presence([:to, :cc])
- |> validate_actors_match(meta)
- |> validate_context_match(meta)
+ |> validate_actors_match(object)
+ |> validate_context_match(object)
+ |> validate_addressing_match(object)
|> validate_object_nonexistence()
|> validate_object_containment()
end
@@ -118,8 +120,8 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.CreateGenericValidator do
end)
end
- def validate_actors_match(cng, meta) do
- attributed_to = meta[:object_data]["attributedTo"] || meta[:object_data]["actor"]
+ def validate_actors_match(cng, object) do
+ attributed_to = object["attributedTo"] || object["actor"]
cng
|> validate_change(:actor, fn :actor, actor ->
@@ -131,7 +133,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.CreateGenericValidator do
end)
end
- def validate_context_match(cng, %{object_data: %{"context" => object_context}}) do
+ def validate_context_match(cng, %{"context" => object_context}) do
cng
|> validate_change(:context, fn :context, context ->
if context == object_context do
@@ -142,5 +144,18 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.CreateGenericValidator do
end)
end
- def validate_context_match(cng, _), do: cng
+ def validate_addressing_match(cng, object) do
+ [:to, :cc, :bcc, :bto]
+ |> Enum.reduce(cng, fn field, cng ->
+ object_data = object[to_string(field)]
+
+ validate_change(cng, field, fn field, data ->
+ if data == object_data do
+ []
+ else
+ [{field, "field doesn't match with object (#{inspect(object_data)})"}]
+ end
+ end)
+ end)
+ end
end
diff --git a/lib/pleroma/web/activity_pub/object_validators/create_note_validator.ex b/lib/pleroma/web/activity_pub/object_validators/create_note_validator.ex
deleted file mode 100644
index a85a0298c..000000000
--- a/lib/pleroma/web/activity_pub/object_validators/create_note_validator.ex
+++ /dev/null
@@ -1,29 +0,0 @@
-# Pleroma: A lightweight social networking server
-# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
-# SPDX-License-Identifier: AGPL-3.0-only
-
-defmodule Pleroma.Web.ActivityPub.ObjectValidators.CreateNoteValidator do
- use Ecto.Schema
-
- alias Pleroma.EctoType.ActivityPub.ObjectValidators
- alias Pleroma.Web.ActivityPub.ObjectValidators.NoteValidator
-
- import Ecto.Changeset
-
- @primary_key false
-
- embedded_schema do
- field(:id, ObjectValidators.ObjectID, primary_key: true)
- field(:actor, ObjectValidators.ObjectID)
- field(:type, :string)
- field(:to, ObjectValidators.Recipients, default: [])
- field(:cc, ObjectValidators.Recipients, default: [])
- field(:bto, ObjectValidators.Recipients, default: [])
- field(:bcc, ObjectValidators.Recipients, default: [])
- embeds_one(:object, NoteValidator)
- end
-
- def cast_data(data) do
- cast(%__MODULE__{}, data, __schema__(:fields))
- end
-end
diff --git a/lib/pleroma/web/activity_pub/object_validators/delete_validator.ex b/lib/pleroma/web/activity_pub/object_validators/delete_validator.ex
index fc1a79a72..7da67bf16 100644
--- a/lib/pleroma/web/activity_pub/object_validators/delete_validator.ex
+++ b/lib/pleroma/web/activity_pub/object_validators/delete_validator.ex
@@ -53,7 +53,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.DeleteValidator do
Tombstone
Video
}
- def validate_data(cng) do
+ defp validate_data(cng) do
cng
|> validate_required([:id, :type, :actor, :to, :cc, :object])
|> validate_inclusion(:type, ["Delete"])
diff --git a/lib/pleroma/web/activity_pub/object_validators/emoji_react_validator.ex b/lib/pleroma/web/activity_pub/object_validators/emoji_react_validator.ex
index 1906e597e..ec7566515 100644
--- a/lib/pleroma/web/activity_pub/object_validators/emoji_react_validator.ex
+++ b/lib/pleroma/web/activity_pub/object_validators/emoji_react_validator.ex
@@ -70,7 +70,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.EmojiReactValidator do
end
end
- def validate_data(data_cng) do
+ defp validate_data(data_cng) do
data_cng
|> validate_inclusion(:type, ["EmojiReact"])
|> validate_required([:id, :type, :object, :actor, :context, :to, :cc, :content])
diff --git a/lib/pleroma/web/activity_pub/object_validators/event_validator.ex b/lib/pleroma/web/activity_pub/object_validators/event_validator.ex
index 2e26726f8..fee2e997a 100644
--- a/lib/pleroma/web/activity_pub/object_validators/event_validator.ex
+++ b/lib/pleroma/web/activity_pub/object_validators/event_validator.ex
@@ -9,6 +9,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.EventValidator do
alias Pleroma.Web.ActivityPub.ObjectValidators.AttachmentValidator
alias Pleroma.Web.ActivityPub.ObjectValidators.CommonFixes
alias Pleroma.Web.ActivityPub.ObjectValidators.CommonValidations
+ alias Pleroma.Web.ActivityPub.ObjectValidators.TagValidator
alias Pleroma.Web.ActivityPub.Transmogrifier
import Ecto.Changeset
@@ -23,8 +24,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.EventValidator do
field(:cc, ObjectValidators.Recipients, default: [])
field(:bto, ObjectValidators.Recipients, default: [])
field(:bcc, ObjectValidators.Recipients, default: [])
- # TODO: Write type
- field(:tag, {:array, :map}, default: [])
+ embeds_many(:tag, TagValidator)
field(:type, :string)
field(:name, :string)
@@ -72,8 +72,8 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.EventValidator do
defp fix(data) do
data
- |> CommonFixes.fix_defaults()
- |> CommonFixes.fix_attribution()
+ |> CommonFixes.fix_actor()
+ |> CommonFixes.fix_object_defaults()
|> Transmogrifier.fix_emoji()
end
@@ -81,11 +81,12 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.EventValidator do
data = fix(data)
struct
- |> cast(data, __schema__(:fields) -- [:attachment])
+ |> cast(data, __schema__(:fields) -- [:attachment, :tag])
|> cast_embed(:attachment)
+ |> cast_embed(:tag)
end
- def validate_data(data_cng) do
+ defp validate_data(data_cng) do
data_cng
|> validate_inclusion(:type, ["Event"])
|> validate_required([:id, :actor, :attributedTo, :type, :context, :context_id])
diff --git a/lib/pleroma/web/activity_pub/object_validators/follow_validator.ex b/lib/pleroma/web/activity_pub/object_validators/follow_validator.ex
index 6e428bacc..239cee5e7 100644
--- a/lib/pleroma/web/activity_pub/object_validators/follow_validator.ex
+++ b/lib/pleroma/web/activity_pub/object_validators/follow_validator.ex
@@ -27,7 +27,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.FollowValidator do
|> cast(data, __schema__(:fields))
end
- def validate_data(cng) do
+ defp validate_data(cng) do
cng
|> validate_required([:id, :type, :actor, :to, :cc, :object])
|> validate_inclusion(:type, ["Follow"])
diff --git a/lib/pleroma/web/activity_pub/object_validators/like_validator.ex b/lib/pleroma/web/activity_pub/object_validators/like_validator.ex
index 30c40b238..509da507b 100644
--- a/lib/pleroma/web/activity_pub/object_validators/like_validator.ex
+++ b/lib/pleroma/web/activity_pub/object_validators/like_validator.ex
@@ -76,7 +76,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.LikeValidator do
end
end
- def validate_data(data_cng) do
+ defp validate_data(data_cng) do
data_cng
|> validate_inclusion(:type, ["Like"])
|> validate_required([:id, :type, :object, :actor, :context, :to, :cc])
diff --git a/lib/pleroma/web/activity_pub/object_validators/question_validator.ex b/lib/pleroma/web/activity_pub/object_validators/question_validator.ex
index 6b746c997..083d08ec4 100644
--- a/lib/pleroma/web/activity_pub/object_validators/question_validator.ex
+++ b/lib/pleroma/web/activity_pub/object_validators/question_validator.ex
@@ -10,6 +10,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.QuestionValidator do
alias Pleroma.Web.ActivityPub.ObjectValidators.CommonFixes
alias Pleroma.Web.ActivityPub.ObjectValidators.CommonValidations
alias Pleroma.Web.ActivityPub.ObjectValidators.QuestionOptionsValidator
+ alias Pleroma.Web.ActivityPub.ObjectValidators.TagValidator
alias Pleroma.Web.ActivityPub.Transmogrifier
import Ecto.Changeset
@@ -24,8 +25,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.QuestionValidator do
field(:cc, ObjectValidators.Recipients, default: [])
field(:bto, ObjectValidators.Recipients, default: [])
field(:bcc, ObjectValidators.Recipients, default: [])
- # TODO: Write type
- field(:tag, {:array, :map}, default: [])
+ embeds_many(:tag, TagValidator)
field(:type, :string)
field(:content, :string)
field(:context, :string)
@@ -83,8 +83,8 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.QuestionValidator do
defp fix(data) do
data
- |> CommonFixes.fix_defaults()
- |> CommonFixes.fix_attribution()
+ |> CommonFixes.fix_actor()
+ |> CommonFixes.fix_object_defaults()
|> Transmogrifier.fix_emoji()
|> fix_closed()
end
@@ -93,13 +93,14 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.QuestionValidator do
data = fix(data)
struct
- |> cast(data, __schema__(:fields) -- [:anyOf, :oneOf, :attachment])
+ |> cast(data, __schema__(:fields) -- [:anyOf, :oneOf, :attachment, :tag])
|> cast_embed(:attachment)
|> cast_embed(:anyOf)
|> cast_embed(:oneOf)
+ |> cast_embed(:tag)
end
- def validate_data(data_cng) do
+ defp validate_data(data_cng) do
data_cng
|> validate_inclusion(:type, ["Question"])
|> validate_required([:id, :actor, :attributedTo, :type, :context, :context_id])
diff --git a/lib/pleroma/web/activity_pub/object_validators/tag_validator.ex b/lib/pleroma/web/activity_pub/object_validators/tag_validator.ex
new file mode 100644
index 000000000..751021585
--- /dev/null
+++ b/lib/pleroma/web/activity_pub/object_validators/tag_validator.ex
@@ -0,0 +1,77 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.Web.ActivityPub.ObjectValidators.TagValidator do
+ use Ecto.Schema
+
+ alias Pleroma.EctoType.ActivityPub.ObjectValidators
+
+ import Ecto.Changeset
+
+ @primary_key false
+ embedded_schema do
+ # Common
+ field(:type, :string)
+ field(:name, :string)
+
+ # Mention, Hashtag
+ field(:href, ObjectValidators.Uri)
+
+ # Emoji
+ embeds_one :icon, IconObjectValidator, primary_key: false do
+ field(:type, :string)
+ field(:url, ObjectValidators.Uri)
+ end
+
+ field(:updated, ObjectValidators.DateTime)
+ field(:id, ObjectValidators.Uri)
+ end
+
+ def cast_and_validate(data) do
+ data
+ |> cast_data()
+ end
+
+ def cast_data(data) do
+ %__MODULE__{}
+ |> changeset(data)
+ end
+
+ def changeset(struct, %{"type" => "Mention"} = data) do
+ struct
+ |> cast(data, [:type, :name, :href])
+ |> validate_required([:type, :href])
+ end
+
+ def changeset(struct, %{"type" => "Hashtag", "name" => name} = data) do
+ name =
+ cond do
+ "#" <> name -> name
+ name -> name
+ end
+ |> String.downcase()
+
+ data = Map.put(data, "name", name)
+
+ struct
+ |> cast(data, [:type, :name, :href])
+ |> validate_required([:type, :name])
+ end
+
+ def changeset(struct, %{"type" => "Emoji"} = data) do
+ data = Map.put(data, "name", String.trim(data["name"], ":"))
+
+ struct
+ |> cast(data, [:type, :name, :updated, :id])
+ |> cast_embed(:icon, with: &icon_changeset/2)
+ |> validate_required([:type, :name, :icon])
+ end
+
+ def icon_changeset(struct, data) do
+ struct
+ |> cast(data, [:type, :url])
+ |> validate_inclusion(:type, ~w[Image])
+ |> validate_required([:type, :url])
+ end
+end
diff --git a/lib/pleroma/web/activity_pub/object_validators/undo_validator.ex b/lib/pleroma/web/activity_pub/object_validators/undo_validator.ex
index 783a79ddb..e8af60ffa 100644
--- a/lib/pleroma/web/activity_pub/object_validators/undo_validator.ex
+++ b/lib/pleroma/web/activity_pub/object_validators/undo_validator.ex
@@ -38,7 +38,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.UndoValidator do
|> cast(data, __schema__(:fields))
end
- def validate_data(data_cng) do
+ defp validate_data(data_cng) do
data_cng
|> validate_inclusion(:type, ["Undo"])
|> validate_required([:id, :type, :object, :actor, :to, :cc])
diff --git a/lib/pleroma/web/activity_pub/object_validators/update_validator.ex b/lib/pleroma/web/activity_pub/object_validators/update_validator.ex
index a66d41400..6bb1dc7fa 100644
--- a/lib/pleroma/web/activity_pub/object_validators/update_validator.ex
+++ b/lib/pleroma/web/activity_pub/object_validators/update_validator.ex
@@ -28,7 +28,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.UpdateValidator do
|> cast(data, __schema__(:fields))
end
- def validate_data(cng) do
+ defp validate_data(cng) do
cng
|> validate_required([:id, :type, :actor, :to, :cc, :object])
|> validate_inclusion(:type, ["Update"])
diff --git a/lib/pleroma/web/activity_pub/pipeline.ex b/lib/pleroma/web/activity_pub/pipeline.ex
index f04557a47..0d6e8aad2 100644
--- a/lib/pleroma/web/activity_pub/pipeline.ex
+++ b/lib/pleroma/web/activity_pub/pipeline.ex
@@ -7,7 +7,11 @@ defmodule Pleroma.Web.ActivityPub.Pipeline do
alias Pleroma.Config
alias Pleroma.Object
alias Pleroma.Repo
- alias Pleroma.Web.ActivityPub
+ alias Pleroma.Utils
+ alias Pleroma.Web.ActivityPub.ActivityPub
+ alias Pleroma.Web.ActivityPub.MRF
+ alias Pleroma.Web.ActivityPub.ObjectValidator
+ alias Pleroma.Web.ActivityPub.SideEffects
alias Pleroma.Web.ActivityPub.Visibility
alias Pleroma.Web.Federator
@@ -21,7 +25,7 @@ defmodule Pleroma.Web.ActivityPub.Pipeline do
@spec common_pipeline(map(), keyword()) ::
{:ok, Activity.t() | Object.t(), keyword()} | {:error, any()}
def common_pipeline(object, meta) do
- case Repo.transaction(fn -> do_common_pipeline(object, meta) end) do
+ case Repo.transaction(fn -> do_common_pipeline(object, meta) end, Utils.query_timeout()) do
{:ok, {:ok, activity, meta}} ->
side_effects().handle_after_transaction(meta)
{:ok, activity, meta}
@@ -37,19 +41,17 @@ defmodule Pleroma.Web.ActivityPub.Pipeline do
end
end
- def do_common_pipeline(object, meta) do
- with {_, {:ok, validated_object, meta}} <-
- {:validate_object, object_validator().validate(object, meta)},
- {_, {:ok, mrfd_object, meta}} <-
- {:mrf_object, mrf().pipeline_filter(validated_object, meta)},
- {_, {:ok, activity, meta}} <-
- {:persist_object, activity_pub().persist(mrfd_object, meta)},
- {_, {:ok, activity, meta}} <-
- {:execute_side_effects, side_effects().handle(activity, meta)},
- {_, {:ok, _}} <- {:federation, maybe_federate(activity, meta)} do
- {:ok, activity, meta}
+ def do_common_pipeline(%{__struct__: _}, _meta), do: {:error, :is_struct}
+
+ def do_common_pipeline(message, meta) do
+ with {_, {:ok, message, meta}} <- {:validate, object_validator().validate(message, meta)},
+ {_, {:ok, message, meta}} <- {:mrf, mrf().pipeline_filter(message, meta)},
+ {_, {:ok, message, meta}} <- {:persist, activity_pub().persist(message, meta)},
+ {_, {:ok, message, meta}} <- {:side_effects, side_effects().handle(message, meta)},
+ {_, {:ok, _}} <- {:federation, maybe_federate(message, meta)} do
+ {:ok, message, meta}
else
- {:mrf_object, {:reject, message, _}} -> {:reject, message}
+ {:mrf, {:reject, message, _}} -> {:reject, message}
e -> {:error, e}
end
end
diff --git a/lib/pleroma/web/activity_pub/side_effects.ex b/lib/pleroma/web/activity_pub/side_effects.ex
index 0b9a9f0c5..674356d9a 100644
--- a/lib/pleroma/web/activity_pub/side_effects.ex
+++ b/lib/pleroma/web/activity_pub/side_effects.ex
@@ -203,6 +203,19 @@ defmodule Pleroma.Web.ActivityPub.SideEffects do
Object.increase_replies_count(in_reply_to)
end
+ reply_depth = (meta[:depth] || 0) + 1
+
+ # FIXME: Force inReplyTo to replies
+ if Pleroma.Web.Federator.allowed_thread_distance?(reply_depth) and
+ object.data["replies"] != nil do
+ for reply_id <- object.data["replies"] do
+ Pleroma.Workers.RemoteFetcherWorker.enqueue("fetch_remote", %{
+ "id" => reply_id,
+ "depth" => reply_depth
+ })
+ end
+ end
+
ConcurrentLimiter.limit(Pleroma.Web.RichMedia.Helpers, fn ->
Task.start(fn -> Pleroma.Web.RichMedia.Helpers.fetch_data_for_activity(activity) end)
end)
@@ -276,10 +289,10 @@ defmodule Pleroma.Web.ActivityPub.SideEffects do
result =
case deleted_object do
%Object{} ->
- with {:ok, deleted_object, activity} <- Object.delete(deleted_object),
+ with {:ok, deleted_object, _activity} <- Object.delete(deleted_object),
{_, actor} when is_binary(actor) <- {:actor, deleted_object.data["actor"]},
%User{} = user <- User.get_cached_by_ap_id(actor) do
- User.remove_pinnned_activity(user, activity)
+ User.remove_pinned_object_id(user, deleted_object.data["id"])
{:ok, user} = ActivityPub.decrease_note_count_if_public(user, deleted_object)
@@ -312,6 +325,63 @@ defmodule Pleroma.Web.ActivityPub.SideEffects do
end
end
+ # Tasks this handles:
+ # - adds pin to user
+ # - removes expiration job for pinned activity, if was set for expiration
+ @impl true
+ def handle(%{data: %{"type" => "Add"} = data} = object, meta) do
+ with %User{} = user <- User.get_cached_by_ap_id(data["actor"]),
+ {:ok, _user} <- User.add_pinned_object_id(user, data["object"]) do
+ # if pinned activity was scheduled for deletion, we remove job
+ if expiration = Pleroma.Workers.PurgeExpiredActivity.get_expiration(meta[:activity_id]) do
+ Oban.cancel_job(expiration.id)
+ end
+
+ {:ok, object, meta}
+ else
+ nil ->
+ {:error, :user_not_found}
+
+ {:error, changeset} ->
+ if changeset.errors[:pinned_objects] do
+ {:error, :pinned_statuses_limit_reached}
+ else
+ changeset.errors
+ end
+ end
+ end
+
+ # Tasks this handles:
+ # - removes pin from user
+ # - removes corresponding Add activity
+ # - if activity had expiration, recreates activity expiration job
+ @impl true
+ def handle(%{data: %{"type" => "Remove"} = data} = object, meta) do
+ with %User{} = user <- User.get_cached_by_ap_id(data["actor"]),
+ {:ok, _user} <- User.remove_pinned_object_id(user, data["object"]) do
+ data["object"]
+ |> Activity.add_by_params_query(user.ap_id, user.featured_address)
+ |> Repo.delete_all()
+
+ # if pinned activity was scheduled for deletion, we reschedule it for deletion
+ if meta[:expires_at] do
+ # MRF.ActivityExpirationPolicy used UTC timestamps for expires_at in original implementation
+ {:ok, expires_at} =
+ Pleroma.EctoType.ActivityPub.ObjectValidators.DateTime.cast(meta[:expires_at])
+
+ Pleroma.Workers.PurgeExpiredActivity.enqueue(%{
+ activity_id: meta[:activity_id],
+ expires_at: expires_at
+ })
+ end
+
+ {:ok, object, meta}
+ else
+ nil -> {:error, :user_not_found}
+ error -> error
+ end
+ end
+
# Nothing to do
@impl true
def handle(object, meta) do
@@ -366,7 +436,7 @@ defmodule Pleroma.Web.ActivityPub.SideEffects do
end
def handle_object_creation(%{"type" => objtype} = object, meta)
- when objtype in ~w[Audio Video Question Event Article] do
+ when objtype in ~w[Audio Video Question Event Article Note] do
with {:ok, object, meta} <- Pipeline.common_pipeline(object, meta) do
{:ok, object, meta}
end
diff --git a/lib/pleroma/web/activity_pub/transmogrifier.ex b/lib/pleroma/web/activity_pub/transmogrifier.ex
index 4d9a5617e..7da29b197 100644
--- a/lib/pleroma/web/activity_pub/transmogrifier.ex
+++ b/lib/pleroma/web/activity_pub/transmogrifier.ex
@@ -32,19 +32,17 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do
"""
def fix_object(object, options \\ []) do
object
- |> strip_internal_fields
- |> fix_actor
- |> fix_url
- |> fix_attachments
- |> fix_context
+ |> strip_internal_fields()
+ |> fix_actor()
+ |> fix_url()
+ |> fix_attachments()
+ |> fix_context()
|> fix_in_reply_to(options)
- |> fix_emoji
- |> fix_tag
- |> set_sensitive
- |> fix_content_map
- |> fix_addressing
- |> fix_summary
- |> fix_type(options)
+ |> fix_emoji()
+ |> fix_tag()
+ |> fix_content_map()
+ |> fix_addressing()
+ |> fix_summary()
end
def fix_summary(%{"summary" => nil} = object) do
@@ -73,17 +71,21 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do
end
end
- def fix_explicit_addressing(
- %{"to" => to, "cc" => cc} = object,
- explicit_mentions,
- follower_collection
- ) do
- explicit_to = Enum.filter(to, fn x -> x in explicit_mentions end)
+ # if directMessage flag is set to true, leave the addressing alone
+ def fix_explicit_addressing(%{"directMessage" => true} = object, _follower_collection),
+ do: object
+
+ def fix_explicit_addressing(%{"to" => to, "cc" => cc} = object, follower_collection) do
+ explicit_mentions =
+ Utils.determine_explicit_mentions(object) ++
+ [Pleroma.Constants.as_public(), follower_collection]
+ explicit_to = Enum.filter(to, fn x -> x in explicit_mentions end)
explicit_cc = Enum.filter(to, fn x -> x not in explicit_mentions end)
final_cc =
(cc ++ explicit_cc)
+ |> Enum.filter(& &1)
|> Enum.reject(fn x -> String.ends_with?(x, "/followers") and x != follower_collection end)
|> Enum.uniq()
@@ -92,29 +94,6 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do
|> Map.put("cc", final_cc)
end
- def fix_explicit_addressing(object, _explicit_mentions, _followers_collection), do: object
-
- # if directMessage flag is set to true, leave the addressing alone
- def fix_explicit_addressing(%{"directMessage" => true} = object), do: object
-
- def fix_explicit_addressing(object) do
- explicit_mentions = Utils.determine_explicit_mentions(object)
-
- %User{follower_address: follower_collection} =
- object
- |> Containment.get_actor()
- |> User.get_cached_by_ap_id()
-
- explicit_mentions =
- explicit_mentions ++
- [
- Pleroma.Constants.as_public(),
- follower_collection
- ]
-
- fix_explicit_addressing(object, explicit_mentions, follower_collection)
- end
-
# if as:Public is addressed, then make sure the followers collection is also addressed
# so that the activities will be delivered to local users.
def fix_implicit_addressing(%{"to" => to, "cc" => cc} = object, followers_collection) do
@@ -138,19 +117,19 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do
end
end
- def fix_implicit_addressing(object, _), do: object
-
def fix_addressing(object) do
- {:ok, %User{} = user} = User.get_or_fetch_by_ap_id(object["actor"])
- followers_collection = User.ap_followers(user)
+ {:ok, %User{follower_address: follower_collection}} =
+ object
+ |> Containment.get_actor()
+ |> User.get_or_fetch_by_ap_id()
object
|> fix_addressing_list("to")
|> fix_addressing_list("cc")
|> fix_addressing_list("bto")
|> fix_addressing_list("bcc")
- |> fix_explicit_addressing()
- |> fix_implicit_addressing(followers_collection)
+ |> fix_explicit_addressing(follower_collection)
+ |> fix_implicit_addressing(follower_collection)
end
def fix_actor(%{"attributedTo" => actor} = object) do
@@ -245,6 +224,8 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do
"type" => Map.get(url || %{}, "type", "Link")
}
|> Maps.put_if_present("mediaType", media_type)
+ |> Maps.put_if_present("width", (url || %{})["width"] || data["width"])
+ |> Maps.put_if_present("height", (url || %{})["height"] || data["height"])
%{
"url" => [attachment_url],
@@ -315,10 +296,9 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do
tags =
tag
|> Enum.filter(fn data -> data["type"] == "Hashtag" and data["name"] end)
- |> Enum.map(fn %{"name" => name} ->
- name
- |> String.slice(1..-1)
- |> String.downcase()
+ |> Enum.map(fn
+ %{"name" => "#" <> hashtag} -> String.downcase(hashtag)
+ %{"name" => hashtag} -> String.downcase(hashtag)
end)
Map.put(object, "tag", tag ++ tags)
@@ -342,19 +322,18 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do
def fix_content_map(object), do: object
- def fix_type(object, options \\ [])
+ defp fix_type(%{"type" => "Note", "inReplyTo" => reply_id, "name" => _} = object, options)
+ when is_binary(reply_id) do
+ options = Keyword.put(options, :fetch, true)
- def fix_type(%{"inReplyTo" => reply_id, "name" => _} = object, options)
- when is_binary(reply_id) do
- with true <- Federator.allowed_thread_distance?(options[:depth]),
- {:ok, %{data: %{"type" => "Question"} = _} = _} <- get_obj_helper(reply_id, options) do
+ with %Object{data: %{"type" => "Question"}} <- Object.normalize(reply_id, options) do
Map.put(object, "type", "Answer")
else
_ -> object
end
end
- def fix_type(object, _), do: object
+ defp fix_type(object, _options), do: object
# Reduce the object list to find the reported user.
defp get_reported(objects) do
@@ -425,10 +404,9 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do
# - tags
# - emoji
def handle_incoming(
- %{"type" => "Create", "object" => %{"type" => objtype} = object} = data,
+ %{"type" => "Create", "object" => %{"type" => "Page"} = object} = data,
options
- )
- when objtype in ~w{Note Page} do
+ ) do
actor = Containment.get_actor(data)
with nil <- Activity.get_create_by_object_ap_id(object["id"]),
@@ -520,14 +498,23 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do
def handle_incoming(
%{"type" => "Create", "object" => %{"type" => objtype, "id" => obj_id}} = data,
- _options
+ options
)
- when objtype in ~w{Question Answer ChatMessage Audio Video Event Article} do
- data = Map.put(data, "object", strip_internal_fields(data["object"]))
+ when objtype in ~w{Question Answer ChatMessage Audio Video Event Article Note} do
+ fetch_options = Keyword.put(options, :depth, (options[:depth] || 0) + 1)
+
+ object =
+ data["object"]
+ |> strip_internal_fields()
+ |> fix_type(fetch_options)
+ |> fix_in_reply_to(fetch_options)
+
+ data = Map.put(data, "object", object)
+ options = Keyword.put(options, :local, false)
with {:ok, %User{}} <- ObjectValidator.fetch_actor(data),
nil <- Activity.get_create_by_object_ap_id(obj_id),
- {:ok, activity, _} <- Pipeline.common_pipeline(data, local: false) do
+ {:ok, activity, _} <- Pipeline.common_pipeline(data, options) do
{:ok, activity}
else
%Activity{} = activity -> {:ok, activity}
@@ -536,7 +523,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do
end
def handle_incoming(%{"type" => type} = data, _options)
- when type in ~w{Like EmojiReact Announce} do
+ when type in ~w{Like EmojiReact Announce Add Remove} do
with :ok <- ObjectValidator.fetch_actor_and_object(data),
{:ok, activity, _meta} <-
Pipeline.common_pipeline(data, local: false) do
@@ -566,7 +553,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do
Pipeline.common_pipeline(data, local: false) do
{:ok, activity}
else
- {:error, {:validate_object, _}} = e ->
+ {:error, {:validate, _}} = e ->
# Check if we have a create activity for this
with {:ok, object_id} <- ObjectValidators.ObjectID.cast(data["object"]),
%Activity{data: %{"actor" => actor}} <-
@@ -742,7 +729,6 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do
# Prepares the object of an outgoing create activity.
def prepare_object(object) do
object
- |> set_sensitive
|> add_hashtags
|> add_mention_tags
|> add_emoji_tags
@@ -933,15 +919,6 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do
Map.put(object, "conversation", object["context"])
end
- def set_sensitive(%{"sensitive" => _} = object) do
- object
- end
-
- def set_sensitive(object) do
- tags = object["tag"] || []
- Map.put(object, "sensitive", "nsfw" in tags)
- end
-
def set_type(%{"type" => "Answer"} = object) do
Map.put(object, "type", "Note")
end
@@ -961,7 +938,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do
object
|> Map.get("attachment", [])
|> Enum.map(fn data ->
- [%{"mediaType" => media_type, "href" => href} | _] = data["url"]
+ [%{"mediaType" => media_type, "href" => href} = url | _] = data["url"]
%{
"url" => href,
@@ -969,6 +946,9 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do
"name" => data["name"],
"type" => "Document"
}
+ |> Maps.put_if_present("width", url["width"])
+ |> Maps.put_if_present("height", url["height"])
+ |> Maps.put_if_present("blurhash", data["blurhash"])
end)
Map.put(object, "attachment", attachments)
@@ -1012,6 +992,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do
with %User{local: false} = user <- User.get_cached_by_ap_id(ap_id),
{:ok, data} <- ActivityPub.fetch_and_prepare_user_from_ap_id(ap_id),
{:ok, user} <- update_user(user, data) do
+ {:ok, _pid} = Task.start(fn -> ActivityPub.pinned_fetch_task(user) end)
TransmogrifierWorker.enqueue("user_upgrade", %{"user_id" => user.id})
{:ok, user}
else
diff --git a/lib/pleroma/web/activity_pub/utils.ex b/lib/pleroma/web/activity_pub/utils.ex
index 0b5f496e3..1df53f79a 100644
--- a/lib/pleroma/web/activity_pub/utils.ex
+++ b/lib/pleroma/web/activity_pub/utils.ex
@@ -37,6 +37,8 @@ defmodule Pleroma.Web.ActivityPub.Utils do
@supported_report_states ~w(open closed resolved)
@valid_visibilities ~w(public unlisted private direct)
+ def as_local_public, do: Endpoint.url() <> "/#Public"
+
# Some implementations send the actor URI as the actor field, others send the entire actor object,
# so figure out what the actor's URI is based on what we have.
def get_ap_id(%{"id" => id} = _), do: id
@@ -95,8 +97,11 @@ defmodule Pleroma.Web.ActivityPub.Utils do
!label_in_collection?(ap_id, params["cc"])
if need_splice? do
- cc_list = extract_list(params["cc"])
- Map.put(params, "cc", [ap_id | cc_list])
+ cc = [ap_id | extract_list(params["cc"])]
+
+ params
+ |> Map.put("cc", cc)
+ |> Maps.safe_put_in(["object", "cc"], cc)
else
params
end
diff --git a/lib/pleroma/web/activity_pub/views/user_view.ex b/lib/pleroma/web/activity_pub/views/user_view.ex
index 8adc9878a..344da19d3 100644
--- a/lib/pleroma/web/activity_pub/views/user_view.ex
+++ b/lib/pleroma/web/activity_pub/views/user_view.ex
@@ -6,8 +6,10 @@ defmodule Pleroma.Web.ActivityPub.UserView do
use Pleroma.Web, :view
alias Pleroma.Keys
+ alias Pleroma.Object
alias Pleroma.Repo
alias Pleroma.User
+ alias Pleroma.Web.ActivityPub.ObjectView
alias Pleroma.Web.ActivityPub.Transmogrifier
alias Pleroma.Web.ActivityPub.Utils
alias Pleroma.Web.Endpoint
@@ -97,6 +99,7 @@ defmodule Pleroma.Web.ActivityPub.UserView do
"followers" => "#{user.ap_id}/followers",
"inbox" => "#{user.ap_id}/inbox",
"outbox" => "#{user.ap_id}/outbox",
+ "featured" => "#{user.ap_id}/collections/featured",
"preferredUsername" => user.nickname,
"name" => user.name,
"summary" => user.bio,
@@ -245,6 +248,25 @@ defmodule Pleroma.Web.ActivityPub.UserView do
|> Map.merge(pagination)
end
+ def render("featured.json", %{
+ user: %{featured_address: featured_address, pinned_objects: pinned_objects}
+ }) do
+ objects =
+ pinned_objects
+ |> Enum.sort_by(fn {_, pinned_at} -> pinned_at end, &>=/2)
+ |> Enum.map(fn {id, _} ->
+ ObjectView.render("object.json", %{object: Object.get_cached_by_ap_id(id)})
+ end)
+
+ %{
+ "id" => featured_address,
+ "type" => "OrderedCollection",
+ "orderedItems" => objects,
+ "totalItems" => length(objects)
+ }
+ |> Map.merge(Utils.make_json_ld_header())
+ end
+
defp maybe_put_total_items(map, false, _total), do: map
defp maybe_put_total_items(map, true, total) do
diff --git a/lib/pleroma/web/activity_pub/visibility.ex b/lib/pleroma/web/activity_pub/visibility.ex
index 00234c0b0..2be59144d 100644
--- a/lib/pleroma/web/activity_pub/visibility.ex
+++ b/lib/pleroma/web/activity_pub/visibility.ex
@@ -20,14 +20,14 @@ defmodule Pleroma.Web.ActivityPub.Visibility do
def is_public?(data) do
Utils.label_in_message?(Pleroma.Constants.as_public(), data) or
- Utils.label_in_message?(Pleroma.Constants.as_local_public(), data)
+ Utils.label_in_message?(Utils.as_local_public(), data)
end
def is_local_public?(%Object{data: data}), do: is_local_public?(data)
def is_local_public?(%Activity{data: data}), do: is_local_public?(data)
def is_local_public?(data) do
- Utils.label_in_message?(Pleroma.Constants.as_local_public(), data) and
+ Utils.label_in_message?(Utils.as_local_public(), data) and
not Utils.label_in_message?(Pleroma.Constants.as_public(), data)
end
@@ -127,7 +127,7 @@ defmodule Pleroma.Web.ActivityPub.Visibility do
Pleroma.Constants.as_public() in cc ->
"unlisted"
- Pleroma.Constants.as_local_public() in to ->
+ Utils.as_local_public() in to ->
"local"
# this should use the sql for the object's activity
diff --git a/lib/pleroma/web/admin_api/controllers/user_controller.ex b/lib/pleroma/web/admin_api/controllers/user_controller.ex
index 65bc63cb9..d3e4c18a3 100644
--- a/lib/pleroma/web/admin_api/controllers/user_controller.ex
+++ b/lib/pleroma/web/admin_api/controllers/user_controller.ex
@@ -13,16 +13,17 @@ defmodule Pleroma.Web.AdminAPI.UserController do
alias Pleroma.Web.ActivityPub.Builder
alias Pleroma.Web.ActivityPub.Pipeline
alias Pleroma.Web.AdminAPI
- alias Pleroma.Web.AdminAPI.AccountView
alias Pleroma.Web.AdminAPI.Search
alias Pleroma.Web.Plugs.OAuthScopesPlug
@users_page_size 50
+ plug(Pleroma.Web.ApiSpec.CastAndValidate)
+
plug(
OAuthScopesPlug,
%{scopes: ["admin:read:accounts"]}
- when action in [:list, :show]
+ when action in [:index, :show]
)
plug(
@@ -44,13 +45,19 @@ defmodule Pleroma.Web.AdminAPI.UserController do
when action in [:follow, :unfollow]
)
+ plug(:put_view, Pleroma.Web.AdminAPI.AccountView)
+
action_fallback(AdminAPI.FallbackController)
- def delete(conn, %{"nickname" => nickname}) do
- delete(conn, %{"nicknames" => [nickname]})
+ defdelegate open_api_operation(action), to: Pleroma.Web.ApiSpec.Admin.UserOperation
+
+ def delete(conn, %{nickname: nickname}) do
+ conn
+ |> Map.put(:body_params, %{nicknames: [nickname]})
+ |> delete(%{})
end
- def delete(%{assigns: %{user: admin}} = conn, %{"nicknames" => nicknames}) do
+ def delete(%{assigns: %{user: admin}, body_params: %{nicknames: nicknames}} = conn, _) do
users = Enum.map(nicknames, &User.get_cached_by_nickname/1)
Enum.each(users, fn user ->
@@ -67,10 +74,16 @@ defmodule Pleroma.Web.AdminAPI.UserController do
json(conn, nicknames)
end
- def follow(%{assigns: %{user: admin}} = conn, %{
- "follower" => follower_nick,
- "followed" => followed_nick
- }) do
+ def follow(
+ %{
+ assigns: %{user: admin},
+ body_params: %{
+ follower: follower_nick,
+ followed: followed_nick
+ }
+ } = conn,
+ _
+ ) do
with %User{} = follower <- User.get_cached_by_nickname(follower_nick),
%User{} = followed <- User.get_cached_by_nickname(followed_nick) do
User.follow(follower, followed)
@@ -86,10 +99,16 @@ defmodule Pleroma.Web.AdminAPI.UserController do
json(conn, "ok")
end
- def unfollow(%{assigns: %{user: admin}} = conn, %{
- "follower" => follower_nick,
- "followed" => followed_nick
- }) do
+ def unfollow(
+ %{
+ assigns: %{user: admin},
+ body_params: %{
+ follower: follower_nick,
+ followed: followed_nick
+ }
+ } = conn,
+ _
+ ) do
with %User{} = follower <- User.get_cached_by_nickname(follower_nick),
%User{} = followed <- User.get_cached_by_nickname(followed_nick) do
User.unfollow(follower, followed)
@@ -105,9 +124,10 @@ defmodule Pleroma.Web.AdminAPI.UserController do
json(conn, "ok")
end
- def create(%{assigns: %{user: admin}} = conn, %{"users" => users}) do
+ def create(%{assigns: %{user: admin}, body_params: %{users: users}} = conn, _) do
changesets =
- Enum.map(users, fn %{"nickname" => nickname, "email" => email, "password" => password} ->
+ users
+ |> Enum.map(fn %{nickname: nickname, email: email, password: password} ->
user_data = %{
nickname: nickname,
name: nickname,
@@ -124,52 +144,49 @@ defmodule Pleroma.Web.AdminAPI.UserController do
end)
case Pleroma.Repo.transaction(changesets) do
- {:ok, users} ->
- res =
- users
+ {:ok, users_map} ->
+ users =
+ users_map
|> Map.values()
|> Enum.map(fn user ->
{:ok, user} = User.post_register_action(user)
user
end)
- |> Enum.map(&AccountView.render("created.json", %{user: &1}))
ModerationLog.insert_log(%{
actor: admin,
- subjects: Map.values(users),
+ subjects: users,
action: "create"
})
- json(conn, res)
+ render(conn, "created_many.json", users: users)
{:error, id, changeset, _} ->
- res =
+ changesets =
Enum.map(changesets.operations, fn
- {current_id, {:changeset, _current_changeset, _}} when current_id == id ->
- AccountView.render("create-error.json", %{changeset: changeset})
+ {^id, {:changeset, _current_changeset, _}} ->
+ changeset
{_, {:changeset, current_changeset, _}} ->
- AccountView.render("create-error.json", %{changeset: current_changeset})
+ current_changeset
end)
conn
|> put_status(:conflict)
- |> json(res)
+ |> render("create_errors.json", changesets: changesets)
end
end
- def show(%{assigns: %{user: admin}} = conn, %{"nickname" => nickname}) do
+ def show(%{assigns: %{user: admin}} = conn, %{nickname: nickname}) do
with %User{} = user <- User.get_cached_by_nickname_or_id(nickname, for: admin) do
- conn
- |> put_view(AccountView)
- |> render("show.json", %{user: user})
+ render(conn, "show.json", %{user: user})
else
_ -> {:error, :not_found}
end
end
- def toggle_activation(%{assigns: %{user: admin}} = conn, %{"nickname" => nickname}) do
+ def toggle_activation(%{assigns: %{user: admin}} = conn, %{nickname: nickname}) do
user = User.get_cached_by_nickname(nickname)
{:ok, updated_user} = User.set_activation(user, !user.is_active)
@@ -182,12 +199,10 @@ defmodule Pleroma.Web.AdminAPI.UserController do
action: action
})
- conn
- |> put_view(AccountView)
- |> render("show.json", %{user: updated_user})
+ render(conn, "show.json", user: updated_user)
end
- def activate(%{assigns: %{user: admin}} = conn, %{"nicknames" => nicknames}) do
+ def activate(%{assigns: %{user: admin}, body_params: %{nicknames: nicknames}} = conn, _) do
users = Enum.map(nicknames, &User.get_cached_by_nickname/1)
{:ok, updated_users} = User.set_activation(users, true)
@@ -197,12 +212,10 @@ defmodule Pleroma.Web.AdminAPI.UserController do
action: "activate"
})
- conn
- |> put_view(AccountView)
- |> render("index.json", %{users: Keyword.values(updated_users)})
+ render(conn, "index.json", users: Keyword.values(updated_users))
end
- def deactivate(%{assigns: %{user: admin}} = conn, %{"nicknames" => nicknames}) do
+ def deactivate(%{assigns: %{user: admin}, body_params: %{nicknames: nicknames}} = conn, _) do
users = Enum.map(nicknames, &User.get_cached_by_nickname/1)
{:ok, updated_users} = User.set_activation(users, false)
@@ -212,12 +225,10 @@ defmodule Pleroma.Web.AdminAPI.UserController do
action: "deactivate"
})
- conn
- |> put_view(AccountView)
- |> render("index.json", %{users: Keyword.values(updated_users)})
+ render(conn, "index.json", users: Keyword.values(updated_users))
end
- def approve(%{assigns: %{user: admin}} = conn, %{"nicknames" => nicknames}) do
+ def approve(%{assigns: %{user: admin}, body_params: %{nicknames: nicknames}} = conn, _) do
users = Enum.map(nicknames, &User.get_cached_by_nickname/1)
{:ok, updated_users} = User.approve(users)
@@ -227,36 +238,27 @@ defmodule Pleroma.Web.AdminAPI.UserController do
action: "approve"
})
- conn
- |> put_view(AccountView)
- |> render("index.json", %{users: updated_users})
+ render(conn, "index.json", users: updated_users)
end
- def list(conn, params) do
+ def index(conn, params) do
{page, page_size} = page_params(params)
- filters = maybe_parse_filters(params["filters"])
+ filters = maybe_parse_filters(params[:filters])
search_params =
%{
- query: params["query"],
+ query: params[:query],
page: page,
page_size: page_size,
- tags: params["tags"],
- name: params["name"],
- email: params["email"],
- actor_types: params["actor_types"]
+ tags: params[:tags],
+ name: params[:name],
+ email: params[:email],
+ actor_types: params[:actor_types]
}
|> Map.merge(filters)
with {:ok, users, count} <- Search.user(search_params) do
- json(
- conn,
- AccountView.render("index.json",
- users: users,
- count: count,
- page_size: page_size
- )
- )
+ render(conn, "index.json", users: users, count: count, page_size: page_size)
end
end
@@ -274,8 +276,8 @@ defmodule Pleroma.Web.AdminAPI.UserController do
defp page_params(params) do
{
- fetch_integer_param(params, "page", 1),
- fetch_integer_param(params, "page_size", @users_page_size)
+ fetch_integer_param(params, :page, 1),
+ fetch_integer_param(params, :page_size, @users_page_size)
}
end
end
diff --git a/lib/pleroma/web/admin_api/views/account_view.ex b/lib/pleroma/web/admin_api/views/account_view.ex
index d7c63d385..e053a9b67 100644
--- a/lib/pleroma/web/admin_api/views/account_view.ex
+++ b/lib/pleroma/web/admin_api/views/account_view.ex
@@ -75,7 +75,7 @@ defmodule Pleroma.Web.AdminAPI.AccountView do
"display_name" => display_name,
"is_active" => user.is_active,
"local" => user.local,
- "roles" => User.roles(user),
+ "roles" => roles(user),
"tags" => user.tags || [],
"is_confirmed" => user.is_confirmed,
"is_approved" => user.is_approved,
@@ -85,6 +85,10 @@ defmodule Pleroma.Web.AdminAPI.AccountView do
}
end
+ def render("created_many.json", %{users: users}) do
+ render_many(users, AccountView, "created.json", as: :user)
+ end
+
def render("created.json", %{user: user}) do
%{
type: "success",
@@ -96,7 +100,11 @@ defmodule Pleroma.Web.AdminAPI.AccountView do
}
end
- def render("create-error.json", %{changeset: %Ecto.Changeset{changes: changes, errors: errors}}) do
+ def render("create_errors.json", %{changesets: changesets}) do
+ render_many(changesets, AccountView, "create_error.json", as: :changeset)
+ end
+
+ def render("create_error.json", %{changeset: %Ecto.Changeset{changes: changes, errors: errors}}) do
%{
type: "error",
code: 409,
@@ -140,4 +148,11 @@ defmodule Pleroma.Web.AdminAPI.AccountView do
defp image_url(%{"url" => [%{"href" => href} | _]}), do: href
defp image_url(_), do: nil
+
+ defp roles(%{is_moderator: is_moderator, is_admin: is_admin}) do
+ %{
+ admin: is_admin,
+ moderator: is_moderator
+ }
+ end
end
diff --git a/lib/pleroma/web/api_spec.ex b/lib/pleroma/web/api_spec.ex
index adc8762dc..528cd9cf4 100644
--- a/lib/pleroma/web/api_spec.ex
+++ b/lib/pleroma/web/api_spec.ex
@@ -92,9 +92,10 @@ defmodule Pleroma.Web.ApiSpec do
"Invites",
"MediaProxy cache",
"OAuth application managment",
- "Report managment",
"Relays",
- "Status administration"
+ "Report managment",
+ "Status administration",
+ "User administration"
]
},
%{"name" => "Applications", "tags" => ["Applications", "Push subscriptions"]},
diff --git a/lib/pleroma/web/api_spec/cast_and_validate.ex b/lib/pleroma/web/api_spec/cast_and_validate.ex
index a3da856ff..d23a7dcb6 100644
--- a/lib/pleroma/web/api_spec/cast_and_validate.ex
+++ b/lib/pleroma/web/api_spec/cast_and_validate.ex
@@ -15,6 +15,7 @@ defmodule Pleroma.Web.ApiSpec.CastAndValidate do
@behaviour Plug
+ alias OpenApiSpex.Plug.PutApiSpec
alias Plug.Conn
@impl Plug
@@ -25,12 +26,10 @@ defmodule Pleroma.Web.ApiSpec.CastAndValidate do
end
@impl Plug
- def call(%{private: %{open_api_spex: private_data}} = conn, %{
- operation_id: operation_id,
- render_error: render_error
- }) do
- spec = private_data.spec
- operation = private_data.operation_lookup[operation_id]
+
+ def call(conn, %{operation_id: operation_id, render_error: render_error}) do
+ {spec, operation_lookup} = PutApiSpec.get_spec_and_operation_lookup(conn)
+ operation = operation_lookup[operation_id]
content_type =
case Conn.get_req_header(conn, "content-type") do
@@ -43,8 +42,7 @@ defmodule Pleroma.Web.ApiSpec.CastAndValidate do
"application/json"
end
- private_data = Map.put(private_data, :operation_id, operation_id)
- conn = Conn.put_private(conn, :open_api_spex, private_data)
+ conn = Conn.put_private(conn, :operation_id, operation_id)
case cast_and_validate(spec, operation, conn, content_type, strict?()) do
{:ok, conn} ->
@@ -64,25 +62,22 @@ defmodule Pleroma.Web.ApiSpec.CastAndValidate do
private: %{
phoenix_controller: controller,
phoenix_action: action,
- open_api_spex: private_data
+ open_api_spex: %{spec_module: spec_module}
}
} = conn,
opts
) do
+ {spec, operation_lookup} = PutApiSpec.get_spec_and_operation_lookup(conn)
+
operation =
- case private_data.operation_lookup[{controller, action}] do
+ case operation_lookup[{controller, action}] do
nil ->
operation_id = controller.open_api_operation(action).operationId
- operation = private_data.operation_lookup[operation_id]
+ operation = operation_lookup[operation_id]
- operation_lookup =
- private_data.operation_lookup
- |> Map.put({controller, action}, operation)
+ operation_lookup = Map.put(operation_lookup, {controller, action}, operation)
- OpenApiSpex.Plug.Cache.adapter().put(
- private_data.spec_module,
- {private_data.spec, operation_lookup}
- )
+ OpenApiSpex.Plug.Cache.adapter().put(spec_module, {spec, operation_lookup})
operation
diff --git a/lib/pleroma/web/api_spec/operations/admin/user_operation.ex b/lib/pleroma/web/api_spec/operations/admin/user_operation.ex
new file mode 100644
index 000000000..c9d0bfd7c
--- /dev/null
+++ b/lib/pleroma/web/api_spec/operations/admin/user_operation.ex
@@ -0,0 +1,389 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.Web.ApiSpec.Admin.UserOperation do
+ alias OpenApiSpex.Operation
+ alias OpenApiSpex.Schema
+ alias Pleroma.Web.ApiSpec.Schemas.ActorType
+ alias Pleroma.Web.ApiSpec.Schemas.ApiError
+
+ import Pleroma.Web.ApiSpec.Helpers
+
+ def open_api_operation(action) do
+ operation = String.to_existing_atom("#{action}_operation")
+ apply(__MODULE__, operation, [])
+ end
+
+ def index_operation do
+ %Operation{
+ tags: ["User administration"],
+ summary: "List users",
+ operationId: "AdminAPI.UserController.index",
+ security: [%{"oAuth" => ["admin:read:accounts"]}],
+ parameters: [
+ Operation.parameter(:filters, :query, :string, "Comma separated list of filters"),
+ Operation.parameter(:query, :query, :string, "Search users query"),
+ Operation.parameter(:name, :query, :string, "Search by display name"),
+ Operation.parameter(:email, :query, :string, "Search by email"),
+ Operation.parameter(:page, :query, :integer, "Page Number"),
+ Operation.parameter(:page_size, :query, :integer, "Number of users to return per page"),
+ Operation.parameter(
+ :actor_types,
+ :query,
+ %Schema{type: :array, items: ActorType},
+ "Filter by actor type"
+ ),
+ Operation.parameter(
+ :tags,
+ :query,
+ %Schema{type: :array, items: %Schema{type: :string}},
+ "Filter by tags"
+ )
+ | admin_api_params()
+ ],
+ responses: %{
+ 200 =>
+ Operation.response(
+ "Response",
+ "application/json",
+ %Schema{
+ type: :object,
+ properties: %{
+ users: %Schema{type: :array, items: user()},
+ count: %Schema{type: :integer},
+ page_size: %Schema{type: :integer}
+ }
+ }
+ ),
+ 403 => Operation.response("Forbidden", "application/json", ApiError)
+ }
+ }
+ end
+
+ def create_operation do
+ %Operation{
+ tags: ["User administration"],
+ summary: "Create a single or multiple users",
+ operationId: "AdminAPI.UserController.create",
+ security: [%{"oAuth" => ["admin:write:accounts"]}],
+ parameters: admin_api_params(),
+ requestBody:
+ request_body(
+ "Parameters",
+ %Schema{
+ description: "POST body for creating users",
+ type: :object,
+ properties: %{
+ users: %Schema{
+ type: :array,
+ items: %Schema{
+ type: :object,
+ properties: %{
+ nickname: %Schema{type: :string},
+ email: %Schema{type: :string},
+ password: %Schema{type: :string}
+ }
+ }
+ }
+ }
+ }
+ ),
+ responses: %{
+ 200 =>
+ Operation.response("Response", "application/json", %Schema{
+ type: :array,
+ items: %Schema{
+ type: :object,
+ properties: %{
+ code: %Schema{type: :integer},
+ type: %Schema{type: :string},
+ data: %Schema{
+ type: :object,
+ properties: %{
+ email: %Schema{type: :string, format: :email},
+ nickname: %Schema{type: :string}
+ }
+ }
+ }
+ }
+ }),
+ 403 => Operation.response("Forbidden", "application/json", ApiError),
+ 409 =>
+ Operation.response("Conflict", "application/json", %Schema{
+ type: :array,
+ items: %Schema{
+ type: :object,
+ properties: %{
+ code: %Schema{type: :integer},
+ error: %Schema{type: :string},
+ type: %Schema{type: :string},
+ data: %Schema{
+ type: :object,
+ properties: %{
+ email: %Schema{type: :string, format: :email},
+ nickname: %Schema{type: :string}
+ }
+ }
+ }
+ }
+ })
+ }
+ }
+ end
+
+ def show_operation do
+ %Operation{
+ tags: ["User administration"],
+ summary: "Show user",
+ operationId: "AdminAPI.UserController.show",
+ security: [%{"oAuth" => ["admin:read:accounts"]}],
+ parameters: [
+ Operation.parameter(
+ :nickname,
+ :path,
+ :string,
+ "User nickname or ID"
+ )
+ | admin_api_params()
+ ],
+ responses: %{
+ 200 => Operation.response("Response", "application/json", user()),
+ 403 => Operation.response("Forbidden", "application/json", ApiError),
+ 404 => Operation.response("Not Found", "application/json", ApiError)
+ }
+ }
+ end
+
+ def follow_operation do
+ %Operation{
+ tags: ["User administration"],
+ summary: "Follow",
+ operationId: "AdminAPI.UserController.follow",
+ security: [%{"oAuth" => ["admin:write:follows"]}],
+ parameters: admin_api_params(),
+ requestBody:
+ request_body(
+ "Parameters",
+ %Schema{
+ type: :object,
+ properties: %{
+ follower: %Schema{type: :string, description: "Follower nickname"},
+ followed: %Schema{type: :string, description: "Followed nickname"}
+ }
+ }
+ ),
+ responses: %{
+ 200 => Operation.response("Response", "application/json", %Schema{type: :string}),
+ 403 => Operation.response("Forbidden", "application/json", ApiError)
+ }
+ }
+ end
+
+ def unfollow_operation do
+ %Operation{
+ tags: ["User administration"],
+ summary: "Unfollow",
+ operationId: "AdminAPI.UserController.unfollow",
+ security: [%{"oAuth" => ["admin:write:follows"]}],
+ parameters: admin_api_params(),
+ requestBody:
+ request_body(
+ "Parameters",
+ %Schema{
+ type: :object,
+ properties: %{
+ follower: %Schema{type: :string, description: "Follower nickname"},
+ followed: %Schema{type: :string, description: "Followed nickname"}
+ }
+ }
+ ),
+ responses: %{
+ 200 => Operation.response("Response", "application/json", %Schema{type: :string}),
+ 403 => Operation.response("Forbidden", "application/json", ApiError)
+ }
+ }
+ end
+
+ def approve_operation do
+ %Operation{
+ tags: ["User administration"],
+ summary: "Approve multiple users",
+ operationId: "AdminAPI.UserController.approve",
+ security: [%{"oAuth" => ["admin:write:accounts"]}],
+ parameters: admin_api_params(),
+ requestBody:
+ request_body(
+ "Parameters",
+ %Schema{
+ description: "POST body for deleting multiple users",
+ type: :object,
+ properties: %{
+ nicknames: %Schema{
+ type: :array,
+ items: %Schema{type: :string}
+ }
+ }
+ }
+ ),
+ responses: %{
+ 200 =>
+ Operation.response("Response", "application/json", %Schema{
+ type: :object,
+ properties: %{user: %Schema{type: :array, items: user()}}
+ }),
+ 403 => Operation.response("Forbidden", "application/json", ApiError)
+ }
+ }
+ end
+
+ def toggle_activation_operation do
+ %Operation{
+ tags: ["User administration"],
+ summary: "Toggle user activation",
+ operationId: "AdminAPI.UserController.toggle_activation",
+ security: [%{"oAuth" => ["admin:write:accounts"]}],
+ parameters: [
+ Operation.parameter(:nickname, :path, :string, "User nickname")
+ | admin_api_params()
+ ],
+ responses: %{
+ 200 => Operation.response("Response", "application/json", user()),
+ 403 => Operation.response("Forbidden", "application/json", ApiError)
+ }
+ }
+ end
+
+ def activate_operation do
+ %Operation{
+ tags: ["User administration"],
+ summary: "Activate multiple users",
+ operationId: "AdminAPI.UserController.activate",
+ security: [%{"oAuth" => ["admin:write:accounts"]}],
+ parameters: admin_api_params(),
+ requestBody:
+ request_body(
+ "Parameters",
+ %Schema{
+ description: "POST body for deleting multiple users",
+ type: :object,
+ properties: %{
+ nicknames: %Schema{
+ type: :array,
+ items: %Schema{type: :string}
+ }
+ }
+ }
+ ),
+ responses: %{
+ 200 =>
+ Operation.response("Response", "application/json", %Schema{
+ type: :object,
+ properties: %{user: %Schema{type: :array, items: user()}}
+ }),
+ 403 => Operation.response("Forbidden", "application/json", ApiError)
+ }
+ }
+ end
+
+ def deactivate_operation do
+ %Operation{
+ tags: ["User administration"],
+ summary: "Deactivates multiple users",
+ operationId: "AdminAPI.UserController.deactivate",
+ security: [%{"oAuth" => ["admin:write:accounts"]}],
+ parameters: admin_api_params(),
+ requestBody:
+ request_body(
+ "Parameters",
+ %Schema{
+ description: "POST body for deleting multiple users",
+ type: :object,
+ properties: %{
+ nicknames: %Schema{
+ type: :array,
+ items: %Schema{type: :string}
+ }
+ }
+ }
+ ),
+ responses: %{
+ 200 =>
+ Operation.response("Response", "application/json", %Schema{
+ type: :object,
+ properties: %{user: %Schema{type: :array, items: user()}}
+ }),
+ 403 => Operation.response("Forbidden", "application/json", ApiError)
+ }
+ }
+ end
+
+ def delete_operation do
+ %Operation{
+ tags: ["User administration"],
+ summary: "Removes a single or multiple users",
+ operationId: "AdminAPI.UserController.delete",
+ security: [%{"oAuth" => ["admin:write:accounts"]}],
+ parameters: [
+ Operation.parameter(
+ :nickname,
+ :query,
+ :string,
+ "User nickname"
+ )
+ | admin_api_params()
+ ],
+ requestBody:
+ request_body(
+ "Parameters",
+ %Schema{
+ description: "POST body for deleting multiple users",
+ type: :object,
+ properties: %{
+ nicknames: %Schema{
+ type: :array,
+ items: %Schema{type: :string}
+ }
+ }
+ }
+ ),
+ responses: %{
+ 200 =>
+ Operation.response("Response", "application/json", %Schema{
+ description: "Array of nicknames",
+ type: :array,
+ items: %Schema{type: :string}
+ }),
+ 403 => Operation.response("Forbidden", "application/json", ApiError)
+ }
+ }
+ end
+
+ defp user do
+ %Schema{
+ type: :object,
+ properties: %{
+ id: %Schema{type: :string},
+ email: %Schema{type: :string, format: :email},
+ avatar: %Schema{type: :string, format: :uri},
+ nickname: %Schema{type: :string},
+ display_name: %Schema{type: :string},
+ is_active: %Schema{type: :boolean},
+ local: %Schema{type: :boolean},
+ roles: %Schema{
+ type: :object,
+ properties: %{
+ admin: %Schema{type: :boolean},
+ moderator: %Schema{type: :boolean}
+ }
+ },
+ tags: %Schema{type: :array, items: %Schema{type: :string}},
+ is_confirmed: %Schema{type: :boolean},
+ is_approved: %Schema{type: :boolean},
+ url: %Schema{type: :string, format: :uri},
+ registration_reason: %Schema{type: :string, nullable: true},
+ actor_type: %Schema{type: :string}
+ }
+ }
+ end
+end
diff --git a/lib/pleroma/web/api_spec/operations/status_operation.ex b/lib/pleroma/web/api_spec/operations/status_operation.ex
index 40edc747d..802fbef3e 100644
--- a/lib/pleroma/web/api_spec/operations/status_operation.ex
+++ b/lib/pleroma/web/api_spec/operations/status_operation.ex
@@ -59,7 +59,7 @@ defmodule Pleroma.Web.ApiSpec.StatusOperation do
Operation.response(
"Status. When `scheduled_at` is present, ScheduledStatus is returned instead",
"application/json",
- %Schema{oneOf: [Status, ScheduledStatus]}
+ %Schema{anyOf: [Status, ScheduledStatus]}
),
422 => Operation.response("Bad Request / MRF Rejection", "application/json", ApiError)
}
@@ -182,7 +182,34 @@ defmodule Pleroma.Web.ApiSpec.StatusOperation do
parameters: [id_param()],
responses: %{
200 => status_response(),
- 400 => Operation.response("Error", "application/json", ApiError)
+ 400 =>
+ Operation.response("Bad Request", "application/json", %Schema{
+ allOf: [ApiError],
+ title: "Unprocessable Entity",
+ example: %{
+ "error" => "You have already pinned the maximum number of statuses"
+ }
+ }),
+ 404 =>
+ Operation.response("Not found", "application/json", %Schema{
+ allOf: [ApiError],
+ title: "Unprocessable Entity",
+ example: %{
+ "error" => "Record not found"
+ }
+ }),
+ 422 =>
+ Operation.response(
+ "Unprocessable Entity",
+ "application/json",
+ %Schema{
+ allOf: [ApiError],
+ title: "Unprocessable Entity",
+ example: %{
+ "error" => "Someone else's status cannot be pinned"
+ }
+ }
+ )
}
}
end
@@ -197,7 +224,22 @@ defmodule Pleroma.Web.ApiSpec.StatusOperation do
parameters: [id_param()],
responses: %{
200 => status_response(),
- 400 => Operation.response("Error", "application/json", ApiError)
+ 400 =>
+ Operation.response("Bad Request", "application/json", %Schema{
+ allOf: [ApiError],
+ title: "Unprocessable Entity",
+ example: %{
+ "error" => "You have already pinned the maximum number of statuses"
+ }
+ }),
+ 404 =>
+ Operation.response("Not found", "application/json", %Schema{
+ allOf: [ApiError],
+ title: "Unprocessable Entity",
+ example: %{
+ "error" => "Record not found"
+ }
+ })
}
}
end
diff --git a/lib/pleroma/web/api_spec/schemas/boolean_like.ex b/lib/pleroma/web/api_spec/schemas/boolean_like.ex
index eb001c5bb..778158f66 100644
--- a/lib/pleroma/web/api_spec/schemas/boolean_like.ex
+++ b/lib/pleroma/web/api_spec/schemas/boolean_like.ex
@@ -3,6 +3,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.ApiSpec.Schemas.BooleanLike do
+ alias OpenApiSpex.Cast
alias OpenApiSpex.Schema
require OpenApiSpex
@@ -27,10 +28,13 @@ defmodule Pleroma.Web.ApiSpec.Schemas.BooleanLike do
%Schema{type: :boolean},
%Schema{type: :string},
%Schema{type: :integer}
- ]
+ ],
+ "x-validate": __MODULE__
})
- def after_cast(value, _schmea) do
- {:ok, Pleroma.Web.ControllerHelper.truthy_param?(value)}
+ def cast(%Cast{value: value} = context) do
+ context
+ |> Map.put(:value, Pleroma.Web.ControllerHelper.truthy_param?(value))
+ |> Cast.ok()
end
end
diff --git a/lib/pleroma/web/api_spec/schemas/status.ex b/lib/pleroma/web/api_spec/schemas/status.ex
index 42fa98718..3d042dc19 100644
--- a/lib/pleroma/web/api_spec/schemas/status.ex
+++ b/lib/pleroma/web/api_spec/schemas/status.ex
@@ -194,6 +194,13 @@ defmodule Pleroma.Web.ApiSpec.Schemas.Status do
parent_visible: %Schema{
type: :boolean,
description: "`true` if the parent post is visible to the user"
+ },
+ pinned_at: %Schema{
+ type: :string,
+ format: "date-time",
+ nullable: true,
+ description:
+ "A datetime (ISO 8601) that states when the post was pinned or `null` if the post is not pinned"
}
}
},
diff --git a/lib/pleroma/web/common_api.ex b/lib/pleroma/web/common_api.ex
index b003e30c7..1b5f8491e 100644
--- a/lib/pleroma/web/common_api.ex
+++ b/lib/pleroma/web/common_api.ex
@@ -228,17 +228,7 @@ defmodule Pleroma.Web.CommonAPI do
{:find_object, _} ->
{:error, :not_found}
- {:common_pipeline,
- {
- :error,
- {
- :validate_object,
- {
- :error,
- changeset
- }
- }
- }} = e ->
+ {:common_pipeline, {:error, {:validate, {:error, changeset}}}} = e ->
if {:object, {"already liked by this actor", []}} in changeset.errors do
{:ok, :already_liked}
else
@@ -411,29 +401,58 @@ defmodule Pleroma.Web.CommonAPI do
end
end
- def pin(id, %{ap_id: user_ap_id} = user) do
- with %Activity{
- actor: ^user_ap_id,
- data: %{"type" => "Create"},
- object: %Object{data: %{"type" => object_type}}
- } = activity <- Activity.get_by_id_with_object(id),
- true <- object_type in ["Note", "Article", "Question"],
- true <- Visibility.is_public?(activity),
- {:ok, _user} <- User.add_pinnned_activity(user, activity) do
+ @spec pin(String.t(), User.t()) :: {:ok, Activity.t()} | {:error, term()}
+ def pin(id, %User{} = user) do
+ with %Activity{} = activity <- create_activity_by_id(id),
+ true <- activity_belongs_to_actor(activity, user.ap_id),
+ true <- object_type_is_allowed_for_pin(activity.object),
+ true <- activity_is_public(activity),
+ {:ok, pin_data, _} <- Builder.pin(user, activity.object),
+ {:ok, _pin, _} <-
+ Pipeline.common_pipeline(pin_data,
+ local: true,
+ activity_id: id
+ ) do
{:ok, activity}
else
- {:error, %{errors: [pinned_activities: {err, _}]}} -> {:error, err}
- _ -> {:error, dgettext("errors", "Could not pin")}
+ {:error, {:side_effects, error}} -> error
+ error -> error
end
end
+ defp create_activity_by_id(id) do
+ with nil <- Activity.create_by_id_with_object(id) do
+ {:error, :not_found}
+ end
+ end
+
+ defp activity_belongs_to_actor(%{actor: actor}, actor), do: true
+ defp activity_belongs_to_actor(_, _), do: {:error, :ownership_error}
+
+ defp object_type_is_allowed_for_pin(%{data: %{"type" => type}}) do
+ with false <- type in ["Note", "Article", "Question"] do
+ {:error, :not_allowed}
+ end
+ end
+
+ defp activity_is_public(activity) do
+ with false <- Visibility.is_public?(activity) do
+ {:error, :visibility_error}
+ end
+ end
+
+ @spec unpin(String.t(), User.t()) :: {:ok, User.t()} | {:error, term()}
def unpin(id, user) do
- with %Activity{data: %{"type" => "Create"}} = activity <- Activity.get_by_id(id),
- {:ok, _user} <- User.remove_pinnned_activity(user, activity) do
+ with %Activity{} = activity <- create_activity_by_id(id),
+ {:ok, unpin_data, _} <- Builder.unpin(user, activity.object),
+ {:ok, _unpin, _} <-
+ Pipeline.common_pipeline(unpin_data,
+ local: true,
+ activity_id: activity.id,
+ expires_at: activity.data["expires_at"],
+ featured_address: user.featured_address
+ ) do
{:ok, activity}
- else
- {:error, %{errors: [pinned_activities: {err, _}]}} -> {:error, err}
- _ -> {:error, dgettext("errors", "Could not unpin")}
end
end
diff --git a/lib/pleroma/web/common_api/activity_draft.ex b/lib/pleroma/web/common_api/activity_draft.ex
index 73f1b0931..80a9fa7bb 100644
--- a/lib/pleroma/web/common_api/activity_draft.ex
+++ b/lib/pleroma/web/common_api/activity_draft.ex
@@ -5,6 +5,7 @@
defmodule Pleroma.Web.CommonAPI.ActivityDraft do
alias Pleroma.Activity
alias Pleroma.Conversation.Participation
+ alias Pleroma.Object
alias Pleroma.Web.CommonAPI
alias Pleroma.Web.CommonAPI.Utils
@@ -179,13 +180,39 @@ defmodule Pleroma.Web.CommonAPI.ActivityDraft do
end
defp sensitive(draft) do
- sensitive = draft.params[:sensitive] || Enum.member?(draft.tags, {"#nsfw", "nsfw"})
+ sensitive = draft.params[:sensitive]
%__MODULE__{draft | sensitive: sensitive}
end
defp object(draft) do
emoji = Map.merge(Pleroma.Emoji.Formatter.get_emoji_map(draft.full_payload), draft.emoji)
+ # Sometimes people create posts with subject containing emoji,
+ # since subjects are usually copied this will result in a broken
+ # subject when someone replies from an instance that does not have
+ # the emoji or has it under different shortcode. This is an attempt
+ # to mitigate this by copying emoji from inReplyTo if they are present
+ # in the subject.
+ summary_emoji =
+ with %Activity{} <- draft.in_reply_to,
+ %Object{data: %{"tag" => [_ | _] = tag}} <- Object.normalize(draft.in_reply_to) do
+ Enum.reduce(tag, %{}, fn
+ %{"type" => "Emoji", "name" => name, "icon" => %{"url" => url}}, acc ->
+ if String.contains?(draft.summary, name) do
+ Map.put(acc, name, url)
+ else
+ acc
+ end
+
+ _, acc ->
+ acc
+ end)
+ else
+ _ -> %{}
+ end
+
+ emoji = Map.merge(emoji, summary_emoji)
+
object =
Utils.make_note_data(draft)
|> Map.put("emoji", emoji)
diff --git a/lib/pleroma/web/common_api/utils.ex b/lib/pleroma/web/common_api/utils.ex
index 9587dfa25..4cc34002d 100644
--- a/lib/pleroma/web/common_api/utils.ex
+++ b/lib/pleroma/web/common_api/utils.ex
@@ -69,7 +69,7 @@ defmodule Pleroma.Web.CommonAPI.Utils do
to =
case visibility do
"public" -> [Pleroma.Constants.as_public() | draft.mentions]
- "local" -> [Pleroma.Constants.as_local_public() | draft.mentions]
+ "local" -> [Utils.as_local_public() | draft.mentions]
end
cc = [draft.user.follower_address]
@@ -217,7 +217,6 @@ defmodule Pleroma.Web.CommonAPI.Utils do
draft.status
|> format_input(content_type, options)
|> maybe_add_attachments(draft.attachments, attachment_links)
- |> maybe_add_nsfw_tag(draft.params)
end
defp get_content_type(content_type) do
@@ -228,13 +227,6 @@ defmodule Pleroma.Web.CommonAPI.Utils do
end
end
- defp maybe_add_nsfw_tag({text, mentions, tags}, %{"sensitive" => sensitive})
- when sensitive in [true, "True", "true", "1"] do
- {text, mentions, [{"#nsfw", "nsfw"} | tags]}
- end
-
- defp maybe_add_nsfw_tag(data, _), do: data
-
def make_context(_, %Participation{} = participation) do
Repo.preload(participation, :conversation).conversation.ap_id
end
@@ -294,7 +286,7 @@ defmodule Pleroma.Web.CommonAPI.Utils do
def format_input(text, "text/markdown", options) do
text
|> Formatter.mentions_escape(options)
- |> Earmark.as_html!(%Earmark.Options{renderer: Pleroma.EarmarkRenderer})
+ |> Formatter.markdown_to_html()
|> Formatter.linkify(options)
|> Formatter.html_escape("text/html")
end
diff --git a/lib/pleroma/web/federator.ex b/lib/pleroma/web/federator.ex
index f5ef76d32..69cfc2d52 100644
--- a/lib/pleroma/web/federator.ex
+++ b/lib/pleroma/web/federator.ex
@@ -96,6 +96,11 @@ defmodule Pleroma.Web.Federator do
Logger.debug("Unhandled actor #{actor}, #{inspect(e)}")
{:error, e}
+ {:error, {:validate_object, _}} = e ->
+ Logger.error("Incoming AP doc validation error: #{inspect(e)}")
+ Logger.debug(Jason.encode!(params, pretty: true))
+ e
+
e ->
# Just drop those for now
Logger.debug(fn -> "Unhandled activity\n" <> Jason.encode!(params, pretty: true) end)
diff --git a/lib/pleroma/web/feed/feed_view.ex b/lib/pleroma/web/feed/feed_view.ex
index 51254ad93..c0fb35e01 100644
--- a/lib/pleroma/web/feed/feed_view.ex
+++ b/lib/pleroma/web/feed/feed_view.ex
@@ -32,6 +32,7 @@ defmodule Pleroma.Web.Feed.FeedView do
%{
activity: activity,
+ object: object,
data: Map.get(object, :data),
actor: actor
}
diff --git a/lib/pleroma/web/mastodon_api/controllers/fallback_controller.ex b/lib/pleroma/web/mastodon_api/controllers/fallback_controller.ex
index d25f84837..84621500e 100644
--- a/lib/pleroma/web/mastodon_api/controllers/fallback_controller.ex
+++ b/lib/pleroma/web/mastodon_api/controllers/fallback_controller.ex
@@ -30,6 +30,12 @@ defmodule Pleroma.Web.MastodonAPI.FallbackController do
|> json(%{error: error_message})
end
+ def call(conn, {:error, status, message}) do
+ conn
+ |> put_status(status)
+ |> json(%{error: message})
+ end
+
def call(conn, _) do
conn
|> put_status(:internal_server_error)
diff --git a/lib/pleroma/web/mastodon_api/controllers/instance_controller.ex b/lib/pleroma/web/mastodon_api/controllers/instance_controller.ex
index 267d0f03b..c7a5267d4 100644
--- a/lib/pleroma/web/mastodon_api/controllers/instance_controller.ex
+++ b/lib/pleroma/web/mastodon_api/controllers/instance_controller.ex
@@ -5,7 +5,7 @@
defmodule Pleroma.Web.MastodonAPI.InstanceController do
use Pleroma.Web, :controller
- plug(OpenApiSpex.Plug.CastAndValidate)
+ plug(Pleroma.Web.ApiSpec.CastAndValidate)
plug(
:skip_plug,
diff --git a/lib/pleroma/web/mastodon_api/controllers/status_controller.ex b/lib/pleroma/web/mastodon_api/controllers/status_controller.ex
index d1a58d5e1..724dc5c5d 100644
--- a/lib/pleroma/web/mastodon_api/controllers/status_controller.ex
+++ b/lib/pleroma/web/mastodon_api/controllers/status_controller.ex
@@ -21,7 +21,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusController do
alias Pleroma.Web.CommonAPI
alias Pleroma.Web.MastodonAPI.AccountView
alias Pleroma.Web.MastodonAPI.ScheduledActivityView
- # alias Pleroma.Web.OAuth.Token
+ alias Pleroma.Web.OAuth.Token
alias Pleroma.Web.Plugs.OAuthScopesPlug
alias Pleroma.Web.Plugs.RateLimiter
@@ -260,6 +260,18 @@ defmodule Pleroma.Web.MastodonAPI.StatusController do
def pin(%{assigns: %{user: user}} = conn, %{id: ap_id_or_id}) do
with {:ok, activity} <- CommonAPI.pin(ap_id_or_id, user) do
try_render(conn, "show.json", activity: activity, for: user, as: :activity)
+ else
+ {:error, :pinned_statuses_limit_reached} ->
+ {:error, "You have already pinned the maximum number of statuses"}
+
+ {:error, :ownership_error} ->
+ {:error, :unprocessable_entity, "Someone else's status cannot be pinned"}
+
+ {:error, :visibility_error} ->
+ {:error, :unprocessable_entity, "Non-public status cannot be pinned"}
+
+ error ->
+ error
end
end
@@ -420,16 +432,14 @@ defmodule Pleroma.Web.MastodonAPI.StatusController do
)
end
- # Deactivated for 2.3.0
- # defp put_application(params,
- # %{assigns: %{token: %Token{user: %User{} = user} = token}} = _conn) do
- # if user.disclose_client do
- # %{client_name: client_name, website: website} = Repo.preload(token, :app).app
- # Map.put(params, :generator, %{type: "Application", name: client_name, url: website})
- # else
- # Map.put(params, :generator, nil)
- # end
- # end
+ defp put_application(params, %{assigns: %{token: %Token{user: %User{} = user} = token}} = _conn) do
+ if user.disclose_client do
+ %{client_name: client_name, website: website} = Repo.preload(token, :app).app
+ Map.put(params, :generator, %{type: "Application", name: client_name, url: website})
+ else
+ Map.put(params, :generator, nil)
+ end
+ end
defp put_application(params, _), do: Map.put(params, :generator, nil)
end
diff --git a/lib/pleroma/web/mastodon_api/controllers/timeline_controller.ex b/lib/pleroma/web/mastodon_api/controllers/timeline_controller.ex
index 3f5849777..845f546d4 100644
--- a/lib/pleroma/web/mastodon_api/controllers/timeline_controller.ex
+++ b/lib/pleroma/web/mastodon_api/controllers/timeline_controller.ex
@@ -131,34 +131,25 @@ defmodule Pleroma.Web.MastodonAPI.TimelineController do
end
defp hashtag_fetching(params, user, local_only) do
- tags =
+ # Note: not sanitizing tag options at this stage (may be mix-cased, have duplicates etc.)
+ tags_any =
[params[:tag], params[:any]]
|> List.flatten()
- |> Enum.uniq()
- |> Enum.reject(&is_nil/1)
- |> Enum.map(&String.downcase/1)
-
- tag_all =
- params
- |> Map.get(:all, [])
- |> Enum.map(&String.downcase/1)
-
- tag_reject =
- params
- |> Map.get(:none, [])
- |> Enum.map(&String.downcase/1)
-
- _activities =
- params
- |> Map.put(:type, "Create")
- |> Map.put(:local_only, local_only)
- |> Map.put(:blocking_user, user)
- |> Map.put(:muting_user, user)
- |> Map.put(:user, user)
- |> Map.put(:tag, tags)
- |> Map.put(:tag_all, tag_all)
- |> Map.put(:tag_reject, tag_reject)
- |> ActivityPub.fetch_public_activities()
+ |> Enum.filter(& &1)
+
+ tag_all = Map.get(params, :all, [])
+ tag_reject = Map.get(params, :none, [])
+
+ params
+ |> Map.put(:type, "Create")
+ |> Map.put(:local_only, local_only)
+ |> Map.put(:blocking_user, user)
+ |> Map.put(:muting_user, user)
+ |> Map.put(:user, user)
+ |> Map.put(:tag, tags_any)
+ |> Map.put(:tag_all, tag_all)
+ |> Map.put(:tag_reject, tag_reject)
+ |> ActivityPub.fetch_public_activities()
end
# GET /api/v1/timelines/tag/:tag
diff --git a/lib/pleroma/web/mastodon_api/views/account_view.ex b/lib/pleroma/web/mastodon_api/views/account_view.ex
index ac25aefdd..9e9de33f6 100644
--- a/lib/pleroma/web/mastodon_api/views/account_view.ex
+++ b/lib/pleroma/web/mastodon_api/views/account_view.ex
@@ -292,6 +292,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountView do
|> maybe_put_allow_following_move(user, opts[:for])
|> maybe_put_unread_conversation_count(user, opts[:for])
|> maybe_put_unread_notification_count(user, opts[:for])
+ |> maybe_put_email_address(user, opts[:for])
end
defp username_from_nickname(string) when is_binary(string) do
@@ -403,6 +404,16 @@ defmodule Pleroma.Web.MastodonAPI.AccountView do
defp maybe_put_unread_notification_count(data, _, _), do: data
+ defp maybe_put_email_address(data, %User{id: user_id}, %User{id: user_id} = user) do
+ Kernel.put_in(
+ data,
+ [:pleroma, :email],
+ user.email
+ )
+ end
+
+ defp maybe_put_email_address(data, _, _), do: data
+
defp image_url(%{"url" => [%{"href" => href} | _]}), do: href
defp image_url(_), do: nil
end
diff --git a/lib/pleroma/web/mastodon_api/views/instance_view.ex b/lib/pleroma/web/mastodon_api/views/instance_view.ex
index 510cac236..005705d97 100644
--- a/lib/pleroma/web/mastodon_api/views/instance_view.ex
+++ b/lib/pleroma/web/mastodon_api/views/instance_view.ex
@@ -23,7 +23,9 @@ defmodule Pleroma.Web.MastodonAPI.InstanceView do
streaming_api: Pleroma.Web.Endpoint.websocket_url()
},
stats: Pleroma.Stats.get_stats(),
- thumbnail: Pleroma.Web.Endpoint.url() <> Keyword.get(instance, :instance_thumbnail),
+ thumbnail:
+ URI.merge(Pleroma.Web.Endpoint.url(), Keyword.get(instance, :instance_thumbnail))
+ |> to_string,
languages: ["en"],
registrations: Keyword.get(instance, :registrations_open),
approval_required: Keyword.get(instance, :account_approval_required),
diff --git a/lib/pleroma/web/mastodon_api/views/status_view.ex b/lib/pleroma/web/mastodon_api/views/status_view.ex
index e8de1ed28..da44e0a74 100644
--- a/lib/pleroma/web/mastodon_api/views/status_view.ex
+++ b/lib/pleroma/web/mastodon_api/views/status_view.ex
@@ -9,6 +9,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusView do
alias Pleroma.Activity
alias Pleroma.HTML
+ alias Pleroma.Maps
alias Pleroma.Object
alias Pleroma.Repo
alias Pleroma.User
@@ -124,16 +125,16 @@ defmodule Pleroma.Web.MastodonAPI.StatusView do
) do
user = CommonAPI.get_user(activity.data["actor"])
created_at = Utils.to_masto_date(activity.data["published"])
- activity_object = Object.normalize(activity, fetch: false)
+ object = Object.normalize(activity, fetch: false)
reblogged_parent_activity =
if opts[:parent_activities] do
Activity.Queries.find_by_object_ap_id(
opts[:parent_activities],
- activity_object.data["id"]
+ object.data["id"]
)
else
- Activity.create_by_object_ap_id(activity_object.data["id"])
+ Activity.create_by_object_ap_id(object.data["id"])
|> Activity.with_preloaded_bookmark(opts[:for])
|> Activity.with_set_thread_muted_field(opts[:for])
|> Repo.one()
@@ -142,7 +143,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusView do
reblog_rendering_opts = Map.put(opts, :activity, reblogged_parent_activity)
reblogged = render("show.json", reblog_rendering_opts)
- favorited = opts[:for] && opts[:for].ap_id in (activity_object.data["likes"] || [])
+ favorited = opts[:for] && opts[:for].ap_id in (object.data["likes"] || [])
bookmarked = Activity.get_bookmark(reblogged_parent_activity, opts[:for]) != nil
@@ -152,10 +153,12 @@ defmodule Pleroma.Web.MastodonAPI.StatusView do
|> Enum.filter(& &1)
|> Enum.map(fn user -> AccountView.render("mention.json", %{user: user}) end)
+ {pinned?, pinned_at} = pin_data(object, user)
+
%{
id: to_string(activity.id),
- uri: activity_object.data["id"],
- url: activity_object.data["id"],
+ uri: object.data["id"],
+ url: object.data["id"],
account:
AccountView.render("show.json", %{
user: user,
@@ -173,18 +176,19 @@ defmodule Pleroma.Web.MastodonAPI.StatusView do
favourited: present?(favorited),
bookmarked: present?(bookmarked),
muted: false,
- pinned: pinned?(activity, user),
+ pinned: pinned?,
sensitive: false,
spoiler_text: "",
visibility: get_visibility(activity),
media_attachments: reblogged[:media_attachments] || [],
mentions: mentions,
tags: reblogged[:tags] || [],
- application: build_application(activity_object.data["generator"]),
+ application: build_application(object.data["generator"]),
language: nil,
emojis: [],
pleroma: %{
- local: activity.local
+ local: activity.local,
+ pinned_at: pinned_at
}
}
end
@@ -198,8 +202,10 @@ defmodule Pleroma.Web.MastodonAPI.StatusView do
like_count = object.data["like_count"] || 0
announcement_count = object.data["announcement_count"] || 0
- tags = object.data["tag"] || []
- sensitive = object.data["sensitive"] || Enum.member?(tags, "nsfw")
+ hashtags = Object.hashtags(object)
+ sensitive = object.data["sensitive"] || Enum.member?(hashtags, "nsfw")
+
+ tags = Object.tags(object)
tag_mentions =
tags
@@ -314,6 +320,8 @@ defmodule Pleroma.Web.MastodonAPI.StatusView do
fn for_user, user -> User.mutes?(for_user, user) end
)
+ {pinned?, pinned_at} = pin_data(object, user)
+
%{
id: to_string(activity.id),
uri: object.data["id"],
@@ -337,7 +345,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusView do
favourited: present?(favorited),
bookmarked: present?(bookmarked),
muted: muted,
- pinned: pinned?(activity, user),
+ pinned: pinned?,
sensitive: sensitive,
spoiler_text: summary,
visibility: get_visibility(object),
@@ -358,7 +366,8 @@ defmodule Pleroma.Web.MastodonAPI.StatusView do
direct_conversation_id: direct_conversation_id,
thread_muted: thread_muted?,
emoji_reactions: emoji_reactions,
- parent_visible: visible_for_user?(reply_to, opts[:for])
+ parent_visible: visible_for_user?(reply_to, opts[:for]),
+ pinned_at: pinned_at
}
}
end
@@ -379,12 +388,15 @@ defmodule Pleroma.Web.MastodonAPI.StatusView do
page_url = page_url_data |> to_string
- image_url =
+ image_url_data =
if is_binary(rich_media["image"]) do
- URI.merge(page_url_data, URI.parse(rich_media["image"]))
- |> to_string
+ URI.parse(rich_media["image"])
+ else
+ nil
end
+ image_url = build_image_url(image_url_data, page_url_data)
+
%{
type: "link",
provider_name: page_url_data.host,
@@ -406,6 +418,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusView do
media_type = attachment_url["mediaType"] || attachment_url["mimeType"] || "image"
href = attachment_url["href"] |> MediaProxy.url()
href_preview = attachment_url["href"] |> MediaProxy.preview_url()
+ meta = render("attachment_meta.json", %{attachment: attachment})
type =
cond do
@@ -428,8 +441,24 @@ defmodule Pleroma.Web.MastodonAPI.StatusView do
pleroma: %{mime_type: media_type},
blurhash: attachment["blurhash"]
}
+ |> Maps.put_if_present(:meta, meta)
+ end
+
+ def render("attachment_meta.json", %{
+ attachment: %{"url" => [%{"width" => width, "height" => height} | _]}
+ })
+ when is_integer(width) and is_integer(height) do
+ %{
+ original: %{
+ width: width,
+ height: height,
+ aspect: width / height
+ }
+ }
end
+ def render("attachment_meta.json", _), do: nil
+
def render("context.json", %{activity: activity, activities: activities, user: user}) do
%{ancestors: ancestors, descendants: descendants} =
activities
@@ -524,8 +553,13 @@ defmodule Pleroma.Web.MastodonAPI.StatusView do
defp present?(false), do: false
defp present?(_), do: true
- defp pinned?(%Activity{id: id}, %User{pinned_activities: pinned_activities}),
- do: id in pinned_activities
+ defp pin_data(%Object{data: %{"id" => object_id}}, %User{pinned_objects: pinned_objects}) do
+ if pinned_at = pinned_objects[object_id] do
+ {true, Utils.to_masto_date(pinned_at)}
+ else
+ {false, nil}
+ end
+ end
defp build_emoji_map(emoji, users, current_user) do
%{
@@ -536,6 +570,27 @@ defmodule Pleroma.Web.MastodonAPI.StatusView do
end
@spec build_application(map() | nil) :: map() | nil
- defp build_application(%{type: _type, name: name, url: url}), do: %{name: name, website: url}
+ defp build_application(%{"type" => _type, "name" => name, "url" => url}),
+ do: %{name: name, website: url}
+
defp build_application(_), do: nil
+
+ # Workaround for Elixir issue #10771
+ # Avoid applying URI.merge unless necessary
+ # TODO: revert to always attempting URI.merge(image_url_data, page_url_data)
+ # when Elixir 1.12 is the minimum supported version
+ @spec build_image_url(struct() | nil, struct()) :: String.t() | nil
+ defp build_image_url(
+ %URI{scheme: image_scheme, host: image_host} = image_url_data,
+ %URI{} = _page_url_data
+ )
+ when not is_nil(image_scheme) and not is_nil(image_host) do
+ image_url_data |> to_string
+ end
+
+ defp build_image_url(%URI{} = image_url_data, %URI{} = page_url_data) do
+ URI.merge(page_url_data, image_url_data) |> to_string
+ end
+
+ defp build_image_url(_, _), do: nil
end
diff --git a/lib/pleroma/web/media_proxy.ex b/lib/pleroma/web/media_proxy.ex
index 7df591201..5c32078aa 100644
--- a/lib/pleroma/web/media_proxy.ex
+++ b/lib/pleroma/web/media_proxy.ex
@@ -121,6 +121,11 @@ defmodule Pleroma.Web.MediaProxy do
end
end
+ def decode_url(encoded) do
+ [_, "proxy", sig, base64 | _] = URI.parse(encoded).path |> String.split("/")
+ decode_url(sig, base64)
+ end
+
defp signed_url(url) do
:crypto.hmac(:sha, Config.get([Endpoint, :secret_key_base]), url)
end
diff --git a/lib/pleroma/web/o_auth/o_auth_view.ex b/lib/pleroma/web/o_auth/o_auth_view.ex
index 281bbcc3c..1419c96a2 100644
--- a/lib/pleroma/web/o_auth/o_auth_view.ex
+++ b/lib/pleroma/web/o_auth/o_auth_view.ex
@@ -10,6 +10,7 @@ defmodule Pleroma.Web.OAuth.OAuthView do
def render("token.json", %{token: token} = opts) do
response = %{
+ id: token.id,
token_type: "Bearer",
access_token: token.token,
refresh_token: token.refresh_token,
diff --git a/lib/pleroma/web/pleroma_api/controllers/backup_controller.ex b/lib/pleroma/web/pleroma_api/controllers/backup_controller.ex
index 315657e9c..fc5d16771 100644
--- a/lib/pleroma/web/pleroma_api/controllers/backup_controller.ex
+++ b/lib/pleroma/web/pleroma_api/controllers/backup_controller.ex
@@ -10,7 +10,7 @@ defmodule Pleroma.Web.PleromaAPI.BackupController do
action_fallback(Pleroma.Web.MastodonAPI.FallbackController)
plug(OAuthScopesPlug, %{scopes: ["read:accounts"]} when action in [:index, :create])
- plug(OpenApiSpex.Plug.CastAndValidate, render_error: Pleroma.Web.ApiSpec.RenderError)
+ plug(Pleroma.Web.ApiSpec.CastAndValidate)
defdelegate open_api_operation(action), to: Pleroma.Web.ApiSpec.PleromaBackupOperation
diff --git a/lib/pleroma/web/pleroma_api/controllers/chat_controller.ex b/lib/pleroma/web/pleroma_api/controllers/chat_controller.ex
index 4adc685fe..dcd54b1af 100644
--- a/lib/pleroma/web/pleroma_api/controllers/chat_controller.ex
+++ b/lib/pleroma/web/pleroma_api/controllers/chat_controller.ex
@@ -38,7 +38,7 @@ defmodule Pleroma.Web.PleromaAPI.ChatController do
%{scopes: ["read:chats"]} when action in [:messages, :index, :index2, :show]
)
- plug(OpenApiSpex.Plug.CastAndValidate, render_error: Pleroma.Web.ApiSpec.RenderError)
+ plug(Pleroma.Web.ApiSpec.CastAndValidate)
defdelegate open_api_operation(action), to: Pleroma.Web.ApiSpec.ChatOperation
diff --git a/lib/pleroma/web/pleroma_api/controllers/user_import_controller.ex b/lib/pleroma/web/pleroma_api/controllers/user_import_controller.ex
index 6d9a11fb6..078d470d9 100644
--- a/lib/pleroma/web/pleroma_api/controllers/user_import_controller.ex
+++ b/lib/pleroma/web/pleroma_api/controllers/user_import_controller.ex
@@ -15,7 +15,7 @@ defmodule Pleroma.Web.PleromaAPI.UserImportController do
plug(OAuthScopesPlug, %{scopes: ["follow", "write:blocks"]} when action == :blocks)
plug(OAuthScopesPlug, %{scopes: ["follow", "write:mutes"]} when action == :mutes)
- plug(OpenApiSpex.Plug.CastAndValidate)
+ plug(Pleroma.Web.ApiSpec.CastAndValidate)
defdelegate open_api_operation(action), to: ApiSpec.UserImportOperation
def follow(%{body_params: %{list: %Plug.Upload{path: path}}} = conn, _) do
diff --git a/lib/pleroma/web/plugs/frontend_static.ex b/lib/pleroma/web/plugs/frontend_static.ex
index e7c943b41..ebe7eaf86 100644
--- a/lib/pleroma/web/plugs/frontend_static.ex
+++ b/lib/pleroma/web/plugs/frontend_static.ex
@@ -10,8 +10,6 @@ defmodule Pleroma.Web.Plugs.FrontendStatic do
"""
@behaviour Plug
- @api_routes Pleroma.Web.Router.get_api_routes()
-
def file_path(path, frontend_type \\ :primary) do
if configuration = Pleroma.Config.get([:frontends, frontend_type]) do
instance_static_path = Pleroma.Config.get([:instance, :static_dir], "instance/static")
@@ -55,10 +53,13 @@ defmodule Pleroma.Web.Plugs.FrontendStatic do
defp invalid_path?([h | t], match), do: String.contains?(h, match) or invalid_path?(t)
defp invalid_path?([], _match), do: false
- defp api_route?([h | _]) when h in @api_routes, do: true
- defp api_route?([_ | t]), do: api_route?(t)
defp api_route?([]), do: false
+ defp api_route?([h | t]) do
+ api_routes = Pleroma.Web.Router.get_api_routes()
+ if h in api_routes, do: true, else: api_route?(t)
+ end
+
defp call_static(conn, opts, from) do
opts = Map.put(opts, :from, from)
Plug.Static.call(conn, opts)
diff --git a/lib/pleroma/web/plugs/http_security_plug.ex b/lib/pleroma/web/plugs/http_security_plug.ex
index 0025b042a..d1e6cc9d3 100644
--- a/lib/pleroma/web/plugs/http_security_plug.ex
+++ b/lib/pleroma/web/plugs/http_security_plug.ex
@@ -48,7 +48,8 @@ defmodule Pleroma.Web.Plugs.HTTPSecurityPlug do
{"x-content-type-options", "nosniff"},
{"referrer-policy", referrer_policy},
{"x-download-options", "noopen"},
- {"content-security-policy", csp_string()}
+ {"content-security-policy", csp_string()},
+ {"permissions-policy", "interest-cohort=()"}
]
headers =
diff --git a/lib/pleroma/web/router.ex b/lib/pleroma/web/router.ex
index 3a091d4bb..95d56699e 100644
--- a/lib/pleroma/web/router.ex
+++ b/lib/pleroma/web/router.ex
@@ -208,7 +208,7 @@ defmodule Pleroma.Web.Router do
get("/users/:nickname/credentials", AdminAPIController, :show_user_credentials)
patch("/users/:nickname/credentials", AdminAPIController, :update_user_credentials)
- get("/users", UserController, :list)
+ get("/users", UserController, :index)
get("/users/:nickname", UserController, :show)
get("/users/:nickname/statuses", AdminAPIController, :list_user_statuses)
get("/users/:nickname/chats", AdminAPIController, :list_user_chats)
@@ -708,6 +708,7 @@ defmodule Pleroma.Web.Router do
# The following two are S2S as well, see `ActivityPub.fetch_follow_information_for_user/1`:
get("/users/:nickname/followers", ActivityPubController, :followers)
get("/users/:nickname/following", ActivityPubController, :following)
+ get("/users/:nickname/collections/featured", ActivityPubController, :pinned)
end
scope "/", Pleroma.Web.ActivityPub do
diff --git a/lib/pleroma/web/templates/feed/feed/_activity.atom.eex b/lib/pleroma/web/templates/feed/feed/_activity.atom.eex
index ca31223fc..57bd92468 100644
--- a/lib/pleroma/web/templates/feed/feed/_activity.atom.eex
+++ b/lib/pleroma/web/templates/feed/feed/_activity.atom.eex
@@ -22,7 +22,7 @@
<link type="text/html" href='<%= @data["external_url"] %>' rel="alternate"/>
<% end %>
- <%= for tag <- @data["tag"] || [] do %>
+ <%= for tag <- Pleroma.Object.hashtags(@object) do %>
<category term="<%= tag %>"></category>
<% end %>
diff --git a/lib/pleroma/web/templates/feed/feed/_activity.rss.eex b/lib/pleroma/web/templates/feed/feed/_activity.rss.eex
index 01dddba07..279f2171d 100644
--- a/lib/pleroma/web/templates/feed/feed/_activity.rss.eex
+++ b/lib/pleroma/web/templates/feed/feed/_activity.rss.eex
@@ -22,7 +22,7 @@
<link rel="ostatus:conversation"><%= activity_context(@activity) %></link>
- <%= for tag <- @data["tag"] || [] do %>
+ <%= for tag <- Pleroma.Object.hashtags(@object) do %>
<category term="<%= tag %>"></category>
<% end %>
diff --git a/lib/pleroma/web/templates/feed/feed/_tag_activity.atom.eex b/lib/pleroma/web/templates/feed/feed/_tag_activity.atom.eex
index 9ae28b48a..aa3035bca 100644
--- a/lib/pleroma/web/templates/feed/feed/_tag_activity.atom.eex
+++ b/lib/pleroma/web/templates/feed/feed/_tag_activity.atom.eex
@@ -41,7 +41,7 @@
<% end %>
<% end %>
- <%= for tag <- @data["tag"] || [] do %>
+ <%= for tag <- Pleroma.Object.hashtags(@object) do %>
<category term="<%= tag %>"></category>
<% end %>
diff --git a/lib/pleroma/web/web_finger.ex b/lib/pleroma/web/web_finger.ex
index 74b236aba..938fc09e3 100644
--- a/lib/pleroma/web/web_finger.ex
+++ b/lib/pleroma/web/web_finger.ex
@@ -94,52 +94,56 @@ defmodule Pleroma.Web.WebFinger do
|> XmlBuilder.to_doc()
end
- defp webfinger_from_xml(doc) do
- subject = XML.string_from_xpath("//Subject", doc)
-
- subscribe_address =
- ~s{//Link[@rel="http://ostatus.org/schema/1.0/subscribe"]/@template}
- |> XML.string_from_xpath(doc)
-
- ap_id =
- ~s{//Link[@rel="self" and @type="application/activity+json"]/@href}
- |> XML.string_from_xpath(doc)
-
- data = %{
- "subject" => subject,
- "subscribe_address" => subscribe_address,
- "ap_id" => ap_id
- }
+ defp webfinger_from_xml(body) do
+ with {:ok, doc} <- XML.parse_document(body) do
+ subject = XML.string_from_xpath("//Subject", doc)
+
+ subscribe_address =
+ ~s{//Link[@rel="http://ostatus.org/schema/1.0/subscribe"]/@template}
+ |> XML.string_from_xpath(doc)
+
+ ap_id =
+ ~s{//Link[@rel="self" and @type="application/activity+json"]/@href}
+ |> XML.string_from_xpath(doc)
+
+ data = %{
+ "subject" => subject,
+ "subscribe_address" => subscribe_address,
+ "ap_id" => ap_id
+ }
- {:ok, data}
+ {:ok, data}
+ end
end
- defp webfinger_from_json(doc) do
- data =
- Enum.reduce(doc["links"], %{"subject" => doc["subject"]}, fn link, data ->
- case {link["type"], link["rel"]} do
- {"application/activity+json", "self"} ->
- Map.put(data, "ap_id", link["href"])
+ defp webfinger_from_json(body) do
+ with {:ok, doc} <- Jason.decode(body) do
+ data =
+ Enum.reduce(doc["links"], %{"subject" => doc["subject"]}, fn link, data ->
+ case {link["type"], link["rel"]} do
+ {"application/activity+json", "self"} ->
+ Map.put(data, "ap_id", link["href"])
- {"application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\"", "self"} ->
- Map.put(data, "ap_id", link["href"])
+ {"application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\"", "self"} ->
+ Map.put(data, "ap_id", link["href"])
- {nil, "http://ostatus.org/schema/1.0/subscribe"} ->
- Map.put(data, "subscribe_address", link["template"])
+ {nil, "http://ostatus.org/schema/1.0/subscribe"} ->
+ Map.put(data, "subscribe_address", link["template"])
- _ ->
- Logger.debug("Unhandled type: #{inspect(link["type"])}")
- data
- end
- end)
+ _ ->
+ Logger.debug("Unhandled type: #{inspect(link["type"])}")
+ data
+ end
+ end)
- {:ok, data}
+ {:ok, data}
+ end
end
def get_template_from_xml(body) do
xpath = "//Link[@rel='lrdd']/@template"
- with doc when doc != :error <- XML.parse_document(body),
+ with {:ok, doc} <- XML.parse_document(body),
template when template != nil <- XML.string_from_xpath(xpath, doc) do
{:ok, template}
end
@@ -192,15 +196,23 @@ defmodule Pleroma.Web.WebFinger do
address,
[{"accept", "application/xrd+xml,application/jrd+json"}]
),
- {:ok, %{status: status, body: body}} when status in 200..299 <- response do
- doc = XML.parse_document(body)
-
- if doc != :error do
- webfinger_from_xml(doc)
- else
- with {:ok, doc} <- Jason.decode(body) do
- webfinger_from_json(doc)
- end
+ {:ok, %{status: status, body: body, headers: headers}} when status in 200..299 <-
+ response do
+ case List.keyfind(headers, "content-type", 0) do
+ {_, content_type} ->
+ case Plug.Conn.Utils.media_type(content_type) do
+ {:ok, "application", subtype, _} when subtype in ~w(xrd+xml xml) ->
+ webfinger_from_xml(body)
+
+ {:ok, "application", subtype, _} when subtype in ~w(jrd+json json) ->
+ webfinger_from_json(body)
+
+ _ ->
+ {:error, {:content_type, content_type}}
+ end
+
+ _ ->
+ {:error, {:content_type, nil}}
end
else
e ->
diff --git a/lib/pleroma/web/xml.ex b/lib/pleroma/web/xml.ex
index 2b34611ac..0ab6e9d32 100644
--- a/lib/pleroma/web/xml.ex
+++ b/lib/pleroma/web/xml.ex
@@ -31,7 +31,7 @@ defmodule Pleroma.Web.XML do
|> :binary.bin_to_list()
|> :xmerl_scan.string(quiet: true)
- doc
+ {:ok, doc}
rescue
_e ->
Logger.debug("Couldn't parse XML: #{inspect(text)}")