fix(webhooks): merge develop and harden delivery

This commit is contained in:
Lain Soykaf 2026-07-26 17:00:14 +04:00
commit 03e75d3b3e
No known key found for this signature in database
254 changed files with 12265 additions and 1143 deletions

View file

@ -540,9 +540,12 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do
# 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)
Pagination.fetch_paginated(query, opts, pagination, pagination_binding(opts))
end
defp pagination_binding(%{favorited_by: _}), do: :favorited_activity
defp pagination_binding(_), do: nil
def fetch_activities(recipients, opts \\ %{}, pagination \\ :keyset) do
list_memberships = Pleroma.List.memberships(opts[:user])
@ -789,6 +792,8 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do
defp restrict_since(query, %{since_id: ""}), do: query
defp restrict_since(query, %{favorited_by: _, since_id: _}), do: query
defp restrict_since(query, %{since_id: since_id}) do
from(activity in query, where: activity.id > ^since_id)
end
@ -896,14 +901,22 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do
|> Repo.all()
# Note: NO extra ordering should be done on "activities.id desc nulls last" for optimal plan
from(
[_activity, object] in query,
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]
)
query =
from(
[_activity, object] in query,
join: hto in "hashtags_objects",
on: hto.object_id == object.id,
where: hto.hashtag_id in ^hashtag_ids
)
if is_nil(query.distinct) do
from([_activity, object] in query,
distinct: [desc: object.id],
order_by: [desc: object.id]
)
else
query
end
end
defp restrict_hashtag_any(query, %{tag: tag}) when is_binary(tag) do
@ -1006,6 +1019,14 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do
defp restrict_state(query, _), do: query
defp restrict_report_target(query, %{report_target_id: actor_id}) do
from(activity in query,
where: fragment("?->'object'->>0 = ?", activity.data, ^actor_id)
)
end
defp restrict_report_target(query, _), do: query
defp restrict_assigned_account(query, %{assigned_account: assigned_account}) do
from(activity in query,
where: fragment("?->>'assigned_account' = ?", activity.data, ^assigned_account)
@ -1015,9 +1036,31 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do
defp restrict_assigned_account(query, _), do: query
defp restrict_favorited_by(query, %{favorited_by: ap_id}) do
newer_favorite =
from(newer_favorite in Activity,
where: newer_favorite.actor == ^ap_id,
where: newer_favorite.id > parent_as(:favorited_activity).id,
where: fragment("?->>'type' = ?", newer_favorite.data, "Like"),
where:
fragment(
"associated_object_id(?) = associated_object_id(?)",
newer_favorite.data,
parent_as(:favorited_activity).data
),
select: 1
)
from(
[_activity, object] in query,
where: fragment("(?)->'likes' \\? (?)", object.data, ^ap_id)
[activity, object: object] in query,
join: favorited_activity in Activity,
as: :favorited_activity,
on:
favorited_activity.actor == ^ap_id and
fragment("?->>'type' = ?", favorited_activity.data, "Like") and
fragment("associated_object_id(?) = (?)->>'id'", favorited_activity.data, object.data),
where: fragment("(?)->'likes' \\? (?)", object.data, ^ap_id),
where: not exists(subquery(newer_favorite)),
select: %Activity{activity | pagination_id: favorited_activity.id}
)
end
@ -1482,6 +1525,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do
|> restrict_actor(opts)
|> restrict_type(opts)
|> restrict_state(opts)
|> restrict_report_target(opts)
|> restrict_assigned_account(opts)
|> restrict_favorited_by(opts)
|> restrict_blocked(restrict_blocked_opts)

View file

@ -309,7 +309,8 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubController do
} = conn,
%{"nickname" => nickname} = params
) do
with {:recipient_exists, %User{} = recipient} <-
with false <- unsupported_http_message_signature?(conn),
{:recipient_exists, %User{} = recipient} <-
{:recipient_exists, User.get_cached_by_nickname(nickname)},
{:sender_exists, {:ok, %User{} = actor}} <-
{:sender_exists, User.get_or_fetch_by_ap_id(params["actor"])},
@ -320,6 +321,9 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubController do
Federator.incoming_ap_doc(params)
json(conn, "ok")
else
true ->
reject_unsupported_http_message_signature(conn)
{:recipient_exists, _} ->
conn
|> put_status(:not_found)
@ -348,20 +352,28 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubController do
end
def inbox(%{assigns: %{valid_signature: true, valid_host_header: true}} = conn, params) do
Federator.incoming_ap_doc(params)
json(conn, "ok")
if unsupported_http_message_signature?(conn) do
reject_unsupported_http_message_signature(conn)
else
Federator.incoming_ap_doc(params)
json(conn, "ok")
end
end
def inbox(%{assigns: %{valid_signature: false}} = conn, params) do
Federator.incoming_failed_signature_ap_doc(%{
method: conn.method,
req_headers: conn.req_headers,
request_path: conn.request_path,
params: params,
query_string: conn.query_string
})
if unsupported_http_message_signature?(conn) do
reject_unsupported_http_message_signature(conn)
else
Federator.incoming_failed_signature_ap_doc(%{
method: conn.method,
req_headers: conn.req_headers,
request_path: conn.request_path,
params: params,
query_string: conn.query_string
})
json(conn, "ok")
json(conn, "ok")
end
end
# POST /relay/inbox -or- POST /internal/fetch/inbox
@ -381,6 +393,27 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubController do
|> json("error, missing HTTP Signature")
end
defp reject_unsupported_http_message_signature(conn) do
conn
|> put_status(:unauthorized)
|> json("error, unsupported HTTP Message Signature")
end
defp unsupported_http_message_signature?(conn) do
signature_headers = Plug.Conn.get_req_header(conn, "signature")
multiple_signature_headers?(signature_headers) or
(Plug.Conn.get_req_header(conn, "signature-input") != [] and
not cavage_signature?(signature_headers))
end
defp multiple_signature_headers?([_, _ | _]), do: true
defp multiple_signature_headers?(_), do: false
defp cavage_signature?(signature_headers) do
Enum.any?(signature_headers, &Regex.match?(~r/(^|,)\s*keyId\s*=/, &1))
end
defp post_inbox_relayed_create(conn, params) do
Logger.debug(
"Signature missing or not from author, relayed Create message, fetching object from source"

View file

@ -6,6 +6,8 @@ defmodule Pleroma.Web.ActivityPub.MRF.ActivityExpirationPolicy do
@moduledoc "Adds expiration to all local Create activities"
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
use Pleroma.Web.ActivityPub.MRF.Policy
@impl true
def filter(activity) do
activity =

View file

@ -3,11 +3,11 @@
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.ActivityPub.MRF.AntiFollowbotPolicy do
@moduledoc "Prevent followbots from following with a bit of heuristic"
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
alias Pleroma.User
@moduledoc "Prevent followbots from following with a bit of heuristic"
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
use Pleroma.Web.ActivityPub.MRF.Policy
# XXX: this should become User.normalize_by_ap_id() or similar, really.
defp normalize_by_ap_id(%{"id" => id}), do: User.get_cached_by_ap_id(id)

View file

@ -3,9 +3,11 @@
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.ActivityPub.MRF.AntiLinkSpamPolicy do
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
alias Pleroma.User
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
use Pleroma.Web.ActivityPub.MRF.Policy
require Logger

View file

@ -3,11 +3,13 @@
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.ActivityPub.MRF.AntiMentionSpamPolicy do
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
alias Pleroma.Config
alias Pleroma.User
require Pleroma.Constants
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
use Pleroma.Web.ActivityPub.MRF.Policy
defp user_has_posted?(%User{} = u), do: u.note_count > 0

View file

@ -3,10 +3,12 @@
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.ActivityPub.MRF.DropPolicy do
require Logger
@moduledoc "Drop and log everything received"
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
require Logger
use Pleroma.Web.ActivityPub.MRF.Policy
@impl true
def filter(activity) do
Logger.debug("REJECTING #{inspect(activity)}")

View file

@ -3,6 +3,8 @@
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.ActivityPub.MRF.EmojiPolicy do
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
require Pleroma.Constants
alias Pleroma.Object.Updater
@ -10,7 +12,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.EmojiPolicy do
@moduledoc "Reject or force-unlisted emojis with certain URLs or names"
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
use Pleroma.Web.ActivityPub.MRF.Policy
defp config_remove_url do
Pleroma.Config.get([:mrf_emoji, :remove_url], [])

View file

@ -3,11 +3,13 @@
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.ActivityPub.MRF.EnsureRePrepended do
alias Pleroma.Object
@moduledoc "Ensure a re: is prepended on replies to a post with a Subject"
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
alias Pleroma.Object
use Pleroma.Web.ActivityPub.MRF.Policy
@reply_prefix Regex.compile!("^re:[[:space:]]*", [:caseless])
def history_awareness, do: :auto

View file

@ -4,12 +4,15 @@
defmodule Pleroma.Web.ActivityPub.MRF.FollowBotPolicy do
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
alias Pleroma.Config
alias Pleroma.User
alias Pleroma.Web.CommonAPI
require Logger
use Pleroma.Web.ActivityPub.MRF.Policy
@impl true
def filter(activity) do
with follower_nickname <- Config.get([:mrf_follow_bot, :follower_nickname]),

View file

@ -3,9 +3,12 @@
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.ActivityPub.MRF.ForceBotUnlistedPolicy do
alias Pleroma.User
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
@moduledoc "Remove bot posts from federated timeline"
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
alias Pleroma.User
use Pleroma.Web.ActivityPub.MRF.Policy
require Pleroma.Constants

View file

@ -3,13 +3,14 @@
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.ActivityPub.MRF.ForceMention do
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
require Pleroma.Constants
alias Pleroma.Config
alias Pleroma.Object
alias Pleroma.User
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
use Pleroma.Web.ActivityPub.MRF.Policy
defp get_author(url) do
with %Object{data: %{"actor" => actor}} <- Object.normalize(url, fetch: false),

View file

@ -3,13 +3,15 @@
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.ActivityPub.MRF.ForceMentionsInContent do
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
require Pleroma.Constants
alias Pleroma.Formatter
alias Pleroma.Object
alias Pleroma.User
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
use Pleroma.Web.ActivityPub.MRF.Policy
@impl true
def history_awareness, do: :auto

View file

@ -3,6 +3,8 @@
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.ActivityPub.MRF.HashtagPolicy do
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
require Pleroma.Constants
alias Pleroma.Config
@ -14,7 +16,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.HashtagPolicy do
Note: This MRF Policy is always enabled, if you want to disable it you have to set empty lists.
"""
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
use Pleroma.Web.ActivityPub.MRF.Policy
@impl true
def history_awareness, do: :manual

View file

@ -3,13 +3,14 @@
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.ActivityPub.MRF.HellthreadPolicy do
@moduledoc "Block activities with too much mentions (configurable)"
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
alias Pleroma.User
require Pleroma.Constants
@moduledoc "Block activities with too much mentions (configurable)"
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
use Pleroma.Web.ActivityPub.MRF.Policy
defp delist_activity(activity, threshold) when threshold > 0 do
follower_collection = User.get_cached_by_ap_id(activity["actor"]).follower_address

View file

@ -6,6 +6,8 @@ defmodule Pleroma.Web.ActivityPub.MRF.InlineQuotePolicy do
@moduledoc "Force a quote line into the message content."
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
use Pleroma.Web.ActivityPub.MRF.Policy
defp build_inline_quote(template, url) do
quote_line = String.replace(template, "{url}", "<a href=\"#{url}\">#{url}</a>")

View file

@ -3,13 +3,14 @@
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.ActivityPub.MRF.KeywordPolicy do
@moduledoc "Reject or Word-Replace activities with a keyword or regex"
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
require Pleroma.Constants
alias Pleroma.Web.ActivityPub.MRF.Utils
@moduledoc "Reject or Word-Replace activities with a keyword or regex"
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
use Pleroma.Web.ActivityPub.MRF.Policy
defp string_matches?(string, pattern) when is_binary(pattern) do
String.contains?(string, pattern)

View file

@ -6,6 +6,8 @@ defmodule Pleroma.Web.ActivityPub.MRF.MediaProxyWarmingPolicy do
@moduledoc "Preloads any attachments in the MediaProxy cache by prefetching them"
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
use Pleroma.Web.ActivityPub.MRF.Policy
alias Pleroma.HTTP
alias Pleroma.Web.MediaProxy

View file

@ -4,9 +4,10 @@
defmodule Pleroma.Web.ActivityPub.MRF.MentionPolicy do
@moduledoc "Block activities which mention a user"
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
use Pleroma.Web.ActivityPub.MRF.Policy
@impl true
def filter(%{"type" => "Create"} = activity) do
reject_actors = Pleroma.Config.get([:mrf_mention, :actors], [])

View file

@ -6,6 +6,8 @@ defmodule Pleroma.Web.ActivityPub.MRF.NoEmptyPolicy do
@moduledoc "Filter local activities which have no content"
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
use Pleroma.Web.ActivityPub.MRF.Policy
alias Pleroma.Web.Endpoint
@impl true

View file

@ -6,6 +6,8 @@ defmodule Pleroma.Web.ActivityPub.MRF.NoOpPolicy do
@moduledoc "Does nothing (lets the messages go through unmodified)"
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
use Pleroma.Web.ActivityPub.MRF.Policy
@impl true
def filter(activity) do
{:ok, activity}

View file

@ -6,6 +6,8 @@ defmodule Pleroma.Web.ActivityPub.MRF.NoPlaceholderTextPolicy do
@moduledoc "Ensure no content placeholder is present (such as the dot from mastodon)"
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
use Pleroma.Web.ActivityPub.MRF.Policy
@impl true
def history_awareness, do: :auto

View file

@ -4,9 +4,11 @@
defmodule Pleroma.Web.ActivityPub.MRF.NormalizeMarkup do
@moduledoc "Scrub configured hypertext markup"
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
alias Pleroma.HTML
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
use Pleroma.Web.ActivityPub.MRF.Policy
@impl true
def history_awareness, do: :auto

View file

@ -38,6 +38,8 @@ defmodule Pleroma.Web.ActivityPub.MRF.NsfwApiPolicy do
- `unlist`: Unlist all detected NSFW content? Default: `false`
- `reject`: Reject all detected NSFW content (takes precedence)? Default: `false`
"""
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
alias Pleroma.Config
alias Pleroma.Constants
alias Pleroma.HTTP
@ -46,7 +48,8 @@ defmodule Pleroma.Web.ActivityPub.MRF.NsfwApiPolicy do
require Logger
require Pleroma.Constants
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
use Pleroma.Web.ActivityPub.MRF.Policy
@policy :mrf_nsfw_api
def build_request_url(url) do

View file

@ -3,13 +3,15 @@
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.ActivityPub.MRF.ObjectAgePolicy do
@moduledoc "Filter activities depending on their age"
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
alias Pleroma.Config
alias Pleroma.User
require Pleroma.Constants
@moduledoc "Filter activities depending on their age"
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
use Pleroma.Web.ActivityPub.MRF.Policy
defp check_date(%{"object" => %{"published" => published}} = activity) do
with %DateTime{} = now <- DateTime.utc_now(),

View file

@ -15,4 +15,12 @@ defmodule Pleroma.Web.ActivityPub.MRF.Policy do
}
@callback history_awareness() :: :auto | :manual
@optional_callbacks config_description: 0, history_awareness: 0, id_filter: 1
defmacro __using__(_) do
quote do
# Otherwise Pleroma.Docs.Generator.list_behaviour_implementations fails
# since the Elixir compiler doesn't automatically load the module since v1.19.
@compile {:autoload, true}
end
end
end

View file

@ -6,11 +6,13 @@ defmodule Pleroma.Web.ActivityPub.MRF.QuietReply do
@moduledoc """
QuietReply alters the scope of activities from local users when replying by enforcing them to be "Unlisted" or "Quiet Public". This delivers the activity to all the expected recipients and instances, but it will not be published in the Federated / The Whole Known Network timelines. It will still be published to the Home timelines of the user's followers and visible to anyone who opens the thread.
"""
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
require Pleroma.Constants
alias Pleroma.User
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
use Pleroma.Web.ActivityPub.MRF.Policy
@impl true
def history_awareness, do: :auto

View file

@ -6,6 +6,8 @@ defmodule Pleroma.Web.ActivityPub.MRF.QuoteToLinkTagPolicy do
@moduledoc "Force a Link tag for posts quoting another post. (may break outgoing federation of quote posts with older Pleroma versions)"
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
use Pleroma.Web.ActivityPub.MRF.Policy
alias Pleroma.Web.ActivityPub.ObjectValidators.CommonFixes
require Pleroma.Constants

View file

@ -4,11 +4,12 @@
defmodule Pleroma.Web.ActivityPub.MRF.RejectNonPublic do
@moduledoc "Rejects non-public (followers-only, direct) activities"
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
alias Pleroma.Config
alias Pleroma.User
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
use Pleroma.Web.ActivityPub.MRF.Policy
require Pleroma.Constants

View file

@ -2,6 +2,8 @@ defmodule Pleroma.Web.ActivityPub.MRF.RemoteReportPolicy do
@moduledoc "Drop remote reports if they don't contain enough information."
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
use Pleroma.Web.ActivityPub.MRF.Policy
alias Pleroma.Config
@impl true

View file

@ -6,6 +6,8 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicy do
@moduledoc "Filter activities depending on their origin instance"
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
use Pleroma.Web.ActivityPub.MRF.Policy
alias Pleroma.Config
alias Pleroma.FollowingRelationship
alias Pleroma.User

View file

@ -3,12 +3,14 @@
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.ActivityPub.MRF.StealEmojiPolicy do
@moduledoc "Detect new emojis by their shortcode and steals them"
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
require Logger
alias Pleroma.Config
@moduledoc "Detect new emojis by their shortcode and steals them"
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
use Pleroma.Web.ActivityPub.MRF.Policy
defp accept_host?(host), do: host in Config.get([:mrf_steal_emoji, :hosts], [])

View file

@ -3,12 +3,14 @@
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.ActivityPub.MRF.SubchainPolicy do
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
alias Pleroma.Config
alias Pleroma.Web.ActivityPub.MRF
require Logger
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
use Pleroma.Web.ActivityPub.MRF.Policy
defp lookup_subchain(actor) do
with matches <- Config.get([:mrf_subchain, :match_actor]),

View file

@ -3,8 +3,6 @@
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.ActivityPub.MRF.TagPolicy do
alias Pleroma.User
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
@moduledoc """
Apply policies based on user tags
@ -18,6 +16,11 @@ defmodule Pleroma.Web.ActivityPub.MRF.TagPolicy do
- `mrf_tag:disable-remote-subscription`: Reject non-local follow requests
- `mrf_tag:disable-any-subscription`: Reject any follow requests
"""
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
alias Pleroma.User
use Pleroma.Web.ActivityPub.MRF.Policy
require Pleroma.Constants

View file

@ -3,11 +3,13 @@
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.ActivityPub.MRF.UserAllowListPolicy do
alias Pleroma.Config
@moduledoc "Accept-list of users from specified instances"
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
alias Pleroma.Config
use Pleroma.Web.ActivityPub.MRF.Policy
defp filter_by_list(activity, []), do: {:ok, activity}
defp filter_by_list(%{"actor" => actor} = activity, allow_list) do

View file

@ -4,9 +4,10 @@
defmodule Pleroma.Web.ActivityPub.MRF.VocabularyPolicy do
@moduledoc "Filter activities which belong to certain activity vocabularies"
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
use Pleroma.Web.ActivityPub.MRF.Policy
@impl true
def filter(%{"type" => "Undo", "object" => object} = activity) do
with {:ok, _} <- filter(object) do

View file

@ -118,6 +118,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidator do
when objtype in ~w[Question Answer Audio Video Image Event Article Note Page] do
with {:ok, object_data} <-
object
|> CommonFixes.maybe_set_attributed_to_from_activity(create_activity)
|> CommonFixes.maybe_add_language_from_activity(create_activity)
|> cast_and_apply_and_stringify_with_history(),
meta = Keyword.put(meta, :object_data, object_data),
@ -172,6 +173,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidator do
{_, {:ok, object_data, _}} <-
{:object_validation,
object
|> CommonFixes.maybe_set_attributed_to_from_activity(update_activity)
|> CommonFixes.maybe_add_language_from_activity(update_activity)
|> validate(meta)},
meta = Keyword.put(meta, :object_data, object_data),

View file

@ -50,7 +50,32 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.ArticleNotePageValidator do
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(%{"url" => url} = data) when is_map(url) do
if is_binary(url["href"]) do
Map.put(data, "url", url["href"])
else
Map.delete(data, "url")
end
end
defp fix_url(%{"url" => url} = data) when is_list(url) do
first_element = Enum.at(url, 0)
url_string =
cond do
is_bitstring(first_element) -> first_element
is_map(first_element) -> first_element["href"]
true -> nil
end
if is_binary(url_string) do
Map.put(data, "url", url_string)
else
Map.delete(data, "url")
end
end
defp fix_url(data), do: data
defp fix_tag(%{"tag" => tag} = data) when is_list(tag) do
@ -79,10 +104,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.ArticleNotePageValidator do
defp fix_replies(data), do: Map.delete(data, "replies")
def fix_attachments(%{"attachment" => attachment} = data) when is_map(attachment),
do: Map.put(data, "attachment", [attachment])
def fix_attachments(data), do: data
def fix_attachments(data), do: Transmogrifier.fix_attachments(data)
defp remote_mention_resolver(
%{"id" => ap_id, "tag" => tags},

View file

@ -41,22 +41,34 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.CommonFixes do
def fix_object_defaults(data) do
data = Maps.filter_empty_values(data)
in_reply_to_id = in_reply_to_id(data["inReplyTo"])
context =
Utils.maybe_create_context(
data["context"] || data["conversation"] || data["inReplyTo"] || data["id"]
data["context"] || data["conversation"] || in_reply_to_id || data["id"]
)
%User{follower_address: follower_collection} = User.get_cached_by_ap_id(data["attributedTo"])
data = Map.put(data, "context", context)
data
|> Map.put("context", context)
|> 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)
with attributed_to when is_binary(attributed_to) <- data["attributedTo"],
%User{follower_address: follower_collection} <- User.get_cached_by_ap_id(attributed_to) do
data
|> 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)
else
_ -> data
end
end
defp in_reply_to_id(in_reply_to) when is_binary(in_reply_to), do: in_reply_to
defp in_reply_to_id(%{"id" => in_reply_to}) when is_binary(in_reply_to), do: in_reply_to
defp in_reply_to_id(%{"href" => in_reply_to}) when is_binary(in_reply_to), do: in_reply_to
defp in_reply_to_id([in_reply_to | _]), do: in_reply_to_id(in_reply_to)
defp in_reply_to_id(_), do: nil
def fix_activity_addressing(activity) do
%User{follower_address: follower_collection} = User.get_cached_by_ap_id(activity["actor"])
@ -79,6 +91,17 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.CommonFixes do
|> Map.put("attributedTo", actor)
end
def maybe_set_attributed_to_from_activity(object, activity) when is_map(object) do
if is_nil(object["attributedTo"]) and is_nil(object["actor"]) do
case Containment.get_actor(activity) do
actor when is_binary(actor) -> Map.put(object, "attributedTo", actor)
_ -> object
end
else
object
end
end
def fix_activity_context(data, %Object{data: %{"context" => object_context}}) do
data
|> Map.put("context", object_context)
@ -96,23 +119,37 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.CommonFixes do
Map.put(data, "to", to)
end
def fix_quote_url(%{"quoteUrl" => _quote_url} = data), do: data
def fix_quote_url(%{"quoteUrl" => quote_url} = data) do
case normalize_object_id(quote_url) do
quote_url when is_binary(quote_url) -> Map.put(data, "quoteUrl", quote_url)
_ -> Map.delete(data, "quoteUrl")
end
end
# Fedibird
# https://github.com/fedibird/mastodon/commit/dbd7ae6cf58a92ec67c512296b4daaea0d01e6ac
def fix_quote_url(%{"quoteUri" => quote_url} = data) do
Map.put(data, "quoteUrl", quote_url)
case normalize_object_id(quote_url) do
quote_url when is_binary(quote_url) -> Map.put(data, "quoteUrl", quote_url)
_ -> data
end
end
# Old Fedibird (bug)
# https://github.com/fedibird/mastodon/issues/9
def fix_quote_url(%{"quoteURL" => quote_url} = data) do
Map.put(data, "quoteUrl", quote_url)
case normalize_object_id(quote_url) do
quote_url when is_binary(quote_url) -> Map.put(data, "quoteUrl", quote_url)
_ -> data
end
end
# Misskey fallback
def fix_quote_url(%{"_misskey_quote" => quote_url} = data) do
Map.put(data, "quoteUrl", quote_url)
case normalize_object_id(quote_url) do
quote_url when is_binary(quote_url) -> Map.put(data, "quoteUrl", quote_url)
_ -> data
end
end
def fix_quote_url(%{"tag" => [_ | _] = tags} = data) do
@ -128,6 +165,11 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.CommonFixes do
def fix_quote_url(data), do: data
defp normalize_object_id(object_id) when is_binary(object_id), do: object_id
defp normalize_object_id(%{"id" => object_id}) when is_binary(object_id), do: object_id
defp normalize_object_id([object_id | _]) when is_binary(object_id), do: object_id
defp normalize_object_id(_), do: nil
# On Mastodon, `"likes"` attribute includes an inlined `Collection` with `totalItems`,
# not a list of users.
# https://github.com/mastodon/mastodon/pull/32007

View file

@ -12,6 +12,8 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.TagValidator do
require Pleroma.Constants
@primary_key false
@tag_types ~w[Mention Hashtag Emoji Link]
embedded_schema do
# Common
field(:type, :string)
@ -49,7 +51,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.TagValidator do
|> validate_required([:type, :href])
end
def changeset(struct, %{"type" => "Hashtag", "name" => name} = data) do
def changeset(struct, %{"type" => "Hashtag", "name" => name} = data) when is_binary(name) do
name = String.downcase(name)
data = Map.put(data, "name", name)
@ -58,13 +60,42 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.TagValidator do
|> validate_required([:type, :name])
end
def changeset(struct, %{"type" => "Emoji"} = data) do
data = Map.put(data, "name", String.trim(data["name"], ":"))
def changeset(struct, %{"type" => "Hashtag"} = data) do
struct
|> cast(data, [:type, :name, :updated, :id])
|> cast_embed(:icon, with: &icon_changeset/2)
|> validate_required([:type, :name, :icon])
|> cast(data, [])
|> Map.put(:action, :ignore)
end
def changeset(struct, %{"type" => "Emoji", "name" => name} = data) when is_binary(name) do
data =
data
|> Map.put("name", String.trim(data["name"], ":"))
|> normalize_emoji_icon()
case data["icon"] do
%{"url" => url} when is_binary(url) ->
if valid_http_url?(url) do
struct
|> cast(data, [:type, :name, :updated, :id])
|> cast_embed(:icon, with: &icon_changeset/2)
|> validate_required([:type, :name, :icon])
else
struct
|> cast(data, [])
|> Map.put(:action, :ignore)
end
_ ->
struct
|> cast(data, [])
|> Map.put(:action, :ignore)
end
end
def changeset(struct, %{"type" => "Emoji"} = data) do
struct
|> cast(data, [])
|> Map.put(:action, :ignore)
end
def changeset(struct, %{"type" => "Link"} = data) do
@ -74,12 +105,80 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.TagValidator do
|> validate_required([:type, :href, :mediaType])
end
def changeset(struct, %{"type" => types} = data) when is_list(types) do
changeset(struct, infer_type(data))
end
def changeset(struct, %{"type" => _} = data) do
struct
|> cast(data, [])
|> Map.put(:action, :ignore)
end
def changeset(struct, data) when is_map(data) do
data = normalize(data)
if Map.has_key?(data, "type") do
changeset(struct, data)
else
struct
|> cast(data, [])
|> Map.put(:action, :ignore)
end
end
def normalize(data) when is_map(data), do: infer_type(data)
defp infer_type(%{"type" => types} = data) when is_list(types) do
type = Enum.find(types, &(&1 in @tag_types)) || Enum.find(types, &is_binary/1)
if type, do: Map.put(data, "type", type), else: Map.delete(data, "type")
end
defp infer_type(%{"type" => _} = data), do: data
defp infer_type(%{"name" => "#" <> _} = data), do: Map.put(data, "type", "Hashtag")
defp infer_type(%{"name" => "@" <> _} = data), do: Map.put(data, "type", "Mention")
defp infer_type(%{"mediaType" => _media_type, "href" => _href} = data),
do: Map.put(data, "type", "Link")
defp infer_type(data), do: data
defp normalize_emoji_icon(%{"icon" => icon} = data) when is_binary(icon) do
Map.put(data, "icon", %{"type" => "Image", "url" => icon})
end
defp normalize_emoji_icon(%{"icon" => icon} = data) when is_map(icon) do
case extract_icon_url(icon) do
url when is_binary(url) -> Map.put(data, "icon", %{"type" => "Image", "url" => url})
_ -> Map.delete(data, "icon")
end
end
defp normalize_emoji_icon(data), do: data
defp extract_icon_url(%{"url" => url}) when is_binary(url), do: url
defp extract_icon_url(%{"url" => %{"href" => href}}) when is_binary(href), do: href
defp extract_icon_url(%{"url" => [first | _]}) do
cond do
is_binary(first) -> first
is_map(first) -> first["href"]
true -> nil
end
end
defp extract_icon_url(%{"href" => href}) when is_binary(href), do: href
defp extract_icon_url(_), do: nil
defp valid_http_url?(url) when is_binary(url) do
match?({:ok, _}, ObjectValidators.Uri.cast(url))
end
defp valid_http_url?(_), do: false
def icon_changeset(struct, data) do
struct
|> cast(data, [:type, :url])

View file

@ -19,6 +19,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do
alias Pleroma.Web.ActivityPub.Builder
alias Pleroma.Web.ActivityPub.ObjectValidator
alias Pleroma.Web.ActivityPub.ObjectValidators.CommonFixes
alias Pleroma.Web.ActivityPub.ObjectValidators.TagValidator
alias Pleroma.Web.ActivityPub.Pipeline
alias Pleroma.Web.ActivityPub.Utils
alias Pleroma.Web.ActivityPub.Visibility
@ -28,6 +29,9 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do
require Pleroma.Constants
@supported_types Pleroma.Constants.activity_types() ++
Pleroma.Constants.object_types() ++ Pleroma.Constants.actor_types()
@doc """
Modifies an incoming AP object (mastodon format) to our internal format.
"""
@ -201,9 +205,29 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do
def fix_in_reply_to(%{"inReplyTo" => in_reply_to} = object, options)
when not is_nil(in_reply_to) do
in_reply_to_id = prepare_in_reply_to(in_reply_to)
object =
cond do
is_list(in_reply_to) ->
if not_empty_string(in_reply_to_id) do
Map.put(object, "inReplyTo", in_reply_to_id)
else
Map.delete(object, "inReplyTo")
end
is_map(in_reply_to) and is_nil(in_reply_to["id"]) and is_binary(in_reply_to["href"]) ->
Map.put(object, "inReplyTo", in_reply_to["href"])
is_map(in_reply_to) and is_nil(in_reply_to["id"]) and is_nil(in_reply_to["href"]) ->
Map.delete(object, "inReplyTo")
true ->
object
end
depth = (options[:depth] || 0) + 1
if Federator.allowed_thread_distance?(depth) do
if not_empty_string(in_reply_to_id) and Federator.allowed_thread_distance?(depth) do
with {:ok, replied_object} <- get_obj_helper(in_reply_to_id, options),
%Activity{} <- Activity.get_create_by_object_ap_id(replied_object.data["id"]) do
object
@ -249,9 +273,17 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do
is_map(in_reply_to) && is_bitstring(in_reply_to["id"]) ->
in_reply_to["id"]
is_map(in_reply_to) && is_bitstring(in_reply_to["href"]) ->
in_reply_to["href"]
is_list(in_reply_to) && is_bitstring(Enum.at(in_reply_to, 0)) ->
Enum.at(in_reply_to, 0)
is_list(in_reply_to) && is_map(Enum.at(in_reply_to, 0)) ->
in_reply_to
|> Enum.at(0)
|> prepare_in_reply_to()
true ->
""
end
@ -265,59 +297,74 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do
|> Map.drop(["conversation"])
end
defp valid_http_url?(href) when is_binary(href) do
match?({:ok, _}, ObjectValidators.Uri.cast(href))
end
defp valid_http_url?(_), do: false
def fix_attachments(%{"attachment" => attachment} = object) when is_list(attachment) do
attachments =
Enum.map(attachment, fn data ->
url =
cond do
is_list(data["url"]) -> List.first(data["url"])
is_map(data["url"]) -> data["url"]
true -> nil
end
Enum.map(attachment, fn
data when is_map(data) ->
url =
cond do
is_list(data["url"]) -> List.first(data["url"])
is_map(data["url"]) -> data["url"]
true -> nil
end
media_type =
cond do
is_map(url) && url =~ Pleroma.Constants.mime_regex() ->
url["mediaType"]
url_data = if is_map(url), do: url, else: %{}
is_bitstring(data["mediaType"]) && data["mediaType"] =~ Pleroma.Constants.mime_regex() ->
data["mediaType"]
media_type =
cond do
is_bitstring(url_data["mediaType"]) &&
url_data["mediaType"] =~ Pleroma.Constants.mime_regex() ->
url_data["mediaType"]
is_bitstring(data["mimeType"]) && data["mimeType"] =~ Pleroma.Constants.mime_regex() ->
data["mimeType"]
is_bitstring(data["mediaType"]) &&
data["mediaType"] =~ Pleroma.Constants.mime_regex() ->
data["mediaType"]
true ->
nil
end
is_bitstring(data["mimeType"]) && data["mimeType"] =~ Pleroma.Constants.mime_regex() ->
data["mimeType"]
href =
cond do
is_map(url) && is_binary(url["href"]) -> url["href"]
is_binary(data["url"]) -> data["url"]
is_binary(data["href"]) -> data["href"]
true -> nil
end
true ->
nil
end
href =
cond do
is_binary(url) -> url
is_binary(url_data["href"]) -> url_data["href"]
is_binary(data["url"]) -> data["url"]
is_binary(data["href"]) -> data["href"]
true -> nil
end
if href && valid_http_url?(href) do
attachment_url =
%{
"href" => href,
"type" => Map.get(url_data, "type", "Link")
}
|> Maps.put_if_present("mediaType", media_type)
|> Maps.put_if_present("width", url_data["width"] || data["width"])
|> Maps.put_if_present("height", url_data["height"] || data["height"])
if href do
attachment_url =
%{
"href" => href,
"type" => Map.get(url || %{}, "type", "Link")
"url" => [attachment_url],
"type" => data["type"] || "Document"
}
|> 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"])
|> Maps.put_if_present("name", data["name"])
|> Maps.put_if_present("blurhash", data["blurhash"])
else
nil
end
%{
"url" => [attachment_url],
"type" => data["type"] || "Document"
}
|> Maps.put_if_present("mediaType", media_type)
|> Maps.put_if_present("name", data["name"])
|> Maps.put_if_present("blurhash", data["blurhash"])
else
_ ->
nil
end
end)
|> Enum.filter(& &1)
@ -351,24 +398,58 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do
def fix_url(object), do: object
defp emoji_icon_url(icon) when is_binary(icon), do: icon
defp emoji_icon_url(%{"url" => url}) when is_binary(url), do: url
defp emoji_icon_url(%{"url" => %{"href" => href}}) when is_binary(href), do: href
defp emoji_icon_url(%{"url" => [first | _]}) do
cond do
is_binary(first) -> first
is_map(first) -> first["href"] || first["url"] || first["id"]
true -> nil
end
end
defp emoji_icon_url(%{"href" => href}) when is_binary(href), do: href
defp emoji_icon_url(_), do: nil
defp valid_emoji_icon_url(icon) do
case emoji_icon_url(icon) do
url when is_binary(url) -> if valid_http_url?(url), do: url
_ -> nil
end
end
def fix_emoji(%{"tag" => tags} = object) when is_list(tags) do
emoji =
tags
|> Enum.filter(fn data -> is_map(data) and data["type"] == "Emoji" and data["icon"] end)
|> Enum.filter(fn data ->
is_map(data) and data["type"] == "Emoji" and is_binary(data["name"]) and data["icon"]
end)
|> Enum.reduce(%{}, fn data, mapping ->
name = String.trim(data["name"], ":")
Map.put(mapping, name, data["icon"]["url"])
case valid_emoji_icon_url(data["icon"]) do
url when is_binary(url) -> Map.put(mapping, name, url)
_ -> mapping
end
end)
Map.put(object, "emoji", emoji)
end
def fix_emoji(%{"tag" => %{"type" => "Emoji"} = tag} = object) do
name = String.trim(tag["name"], ":")
emoji = %{name => tag["icon"]["url"]}
def fix_emoji(%{"tag" => %{"type" => "Emoji", "name" => name} = tag} = object)
when is_binary(name) do
name = String.trim(name, ":")
Map.put(object, "emoji", emoji)
with url when is_binary(url) <- valid_emoji_icon_url(tag["icon"]) do
Map.put(object, "emoji", %{name => url})
else
_ -> object
end
end
def fix_emoji(object), do: object
@ -376,7 +457,9 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do
def fix_tag(%{"tag" => tag} = object) when is_list(tag) do
tags =
tag
|> Enum.filter(fn data -> data["type"] == "Hashtag" and data["name"] end)
|> Enum.filter(fn data ->
is_map(data) and data["type"] == "Hashtag" and is_binary(data["name"])
end)
|> Enum.map(fn
%{"name" => "#" <> hashtag} -> String.downcase(hashtag)
%{"name" => hashtag} -> String.downcase(hashtag)
@ -439,9 +522,37 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do
def handle_incoming(data, options \\ []) do
data
|> fix_recursive(&strip_internal_fields/1)
|> fix_recursive(&fix_type_as_string/1)
|> handle_incoming_normalized(options)
end
defp fix_type_as_string(data) do
data
|> normalize_type()
|> normalize_tag_types()
end
defp normalize_type(%{"type" => types} = data) when is_list(types) do
type = Enum.find(types, &(&1 in @supported_types)) || Enum.find(types, &is_binary/1)
if type, do: Map.put(data, "type", type), else: data
end
defp normalize_type(data), do: data
defp normalize_tag_types(%{"tag" => tags} = data) when is_list(tags) do
Map.put(data, "tag", Enum.map(tags, &normalize_tag_type/1))
end
defp normalize_tag_types(%{"tag" => tag} = data) when is_map(tag) do
Map.put(data, "tag", normalize_tag_type(tag))
end
defp normalize_tag_types(data), do: data
defp normalize_tag_type(tag) when is_map(tag), do: TagValidator.normalize(tag)
defp normalize_tag_type(tag), do: tag
# Flag objects are placed ahead of the ID check because Mastodon 2.8 and earlier send them
# with nil ID.
defp handle_incoming_normalized(

View file

@ -68,7 +68,7 @@ defmodule Pleroma.Web.ActivityPub.UserView do
capabilities =
if is_boolean(user.accepts_chat_messages) do
%{
"acceptsChatMessages" => user.accepts_chat_messages
"acceptsChatMessages" => Pleroma.Chat.enabled?() and user.accepts_chat_messages
}
else
%{}

View file

@ -71,7 +71,11 @@ defmodule Pleroma.Web.AdminAPI.ConfigController do
end
def descriptions(conn, _params) do
descriptions = Enum.filter(Pleroma.Docs.JSON.compiled_descriptions(), &whitelisted_config?/1)
descriptions =
Pleroma.Docs.JSON.compiled_descriptions()
|> Enum.filter(&allowed_config?(&1, :whitelist))
|> Enum.reject(&allowed_config?(&1, :blacklist))
|> Enum.reject(&ConfigDB.static?/1)
json(conn, translate_descriptions(descriptions))
end
@ -89,7 +93,7 @@ defmodule Pleroma.Web.AdminAPI.ConfigController do
def show(conn, _params) do
with :ok <- configurable_from_database() do
configs = ConfigDB.get_all_as_keyword()
configs = ConfigDB.get_all_as_keyword(exclude_static: true)
merged =
Config.Holder.default_config()
@ -120,6 +124,7 @@ defmodule Pleroma.Web.AdminAPI.ConfigController do
end)
end)
|> List.flatten()
|> Enum.reject(&ConfigDB.static?/1)
render(conn, "index.json", %{
configs: merged,
@ -132,7 +137,9 @@ defmodule Pleroma.Web.AdminAPI.ConfigController do
with :ok <- configurable_from_database() do
results =
configs
|> Enum.filter(&whitelisted_config?/1)
|> Enum.filter(&allowed_config?(&1, :whitelist))
|> Enum.reject(&allowed_config?(&1, :blacklist))
|> Enum.reject(&(ConfigDB.static?(&1) and not &1[:delete]))
|> Enum.map(fn
%{group: group, key: key, delete: true} = params ->
ConfigDB.delete(%{group: group, key: key, subkeys: params[:subkeys]})
@ -174,27 +181,34 @@ defmodule Pleroma.Web.AdminAPI.ConfigController do
end
end
defp whitelisted_config?(":pleroma", ":database_config_whitelist"), do: false
defp allowed_config?(":pleroma", ":database_config_whitelist", _), do: true
defp allowed_config?(":pleroma", ":database_config_blacklist", _), do: true
defp whitelisted_config?(group, key) do
if whitelisted_configs = Config.get(:database_config_whitelist) do
Enum.any?(whitelisted_configs, fn
{whitelisted_group} ->
group == inspect(whitelisted_group)
defp allowed_config?(group, key, mode) do
configs =
case mode do
:whitelist -> Config.get(:database_config_whitelist)
:blacklist -> Config.get(:database_config_blacklist)
end
{whitelisted_group, whitelisted_key} ->
group == inspect(whitelisted_group) && key == inspect(whitelisted_key)
if configs do
Enum.any?(configs, fn
{allowed_group} ->
group == inspect(allowed_group)
{allowed_group, allowed_key} ->
group == inspect(allowed_group) && key == inspect(allowed_key)
end)
else
true
end
end
defp whitelisted_config?(%{group: group, key: key}) do
whitelisted_config?(group, key)
defp allowed_config?(%{group: group, key: key}, mode) do
allowed_config?(group, key, mode)
end
defp whitelisted_config?(%{group: group} = config) do
whitelisted_config?(group, config[:key])
defp allowed_config?(%{group: group} = config, mode) do
allowed_config?(group, config[:key], mode)
end
end

View file

@ -109,6 +109,13 @@ defmodule Pleroma.Web.ApiSpec do
"Webhooks"
]
},
%{
"name" => "Administration (Mastodon API)",
"tags" => [
"User administration (Mastodon API)",
"Report management (Mastodon API)"
]
},
%{"name" => "Applications", "tags" => ["Applications", "Push subscriptions"]},
%{
"name" => "Current account",

View file

@ -57,7 +57,7 @@ defmodule Pleroma.Web.ApiSpec.Admin.WebhookOperation do
type: :object,
required: [:url, :events],
properties: %{
url: %Schema{type: :string, format: :uri},
url: %Schema{type: :string, format: :uri, maxLength: 255},
events: event_type(min_items: 1),
enabled: %Schema{type: :boolean}
},
@ -84,7 +84,7 @@ defmodule Pleroma.Web.ApiSpec.Admin.WebhookOperation do
description: "POST body for updating a webhook",
type: :object,
properties: %{
url: %Schema{type: :string, format: :uri},
url: %Schema{type: :string, format: :uri, maxLength: 255},
events: event_type(min_items: 1),
enabled: %Schema{type: :boolean}
},
@ -161,7 +161,7 @@ defmodule Pleroma.Web.ApiSpec.Admin.WebhookOperation do
type: :object,
properties: %{
id: %Schema{type: :string},
url: %Schema{type: :string, format: :uri},
url: %Schema{type: :string, format: :uri, maxLength: 255},
events: event_type(),
secret: %Schema{type: :string},
enabled: %Schema{type: :boolean},

View file

@ -31,7 +31,8 @@ defmodule Pleroma.Web.ApiSpec.ChatOperation do
"The updated chat",
"application/json",
Chat
)
),
404 => Operation.response("Not Found", "application/json", ApiError)
},
security: [
%{
@ -56,7 +57,8 @@ defmodule Pleroma.Web.ApiSpec.ChatOperation do
"The read ChatMessage",
"application/json",
ChatMessage
)
),
404 => Operation.response("Not Found", "application/json", ApiError)
},
security: [
%{
@ -87,7 +89,8 @@ defmodule Pleroma.Web.ApiSpec.ChatOperation do
"The existing chat",
"application/json",
Chat
)
),
404 => Operation.response("Not Found", "application/json", ApiError)
},
security: [
%{
@ -118,7 +121,8 @@ defmodule Pleroma.Web.ApiSpec.ChatOperation do
"The created or existing chat",
"application/json",
Chat
)
),
404 => Operation.response("Not Found", "application/json", ApiError)
},
security: [
%{
@ -146,7 +150,8 @@ defmodule Pleroma.Web.ApiSpec.ChatOperation do
Operation.parameter(:pinned, :query, BooleanLike.schema(), "Include only pinned chats")
],
responses: %{
200 => Operation.response("The chats of the user", "application/json", chats_response())
200 => Operation.response("The chats of the user", "application/json", chats_response()),
404 => Operation.response("Not Found", "application/json", ApiError)
},
security: [
%{
@ -172,7 +177,8 @@ defmodule Pleroma.Web.ApiSpec.ChatOperation do
| pagination_params()
],
responses: %{
200 => Operation.response("The chats of the user", "application/json", chats_response())
200 => Operation.response("The chats of the user", "application/json", chats_response()),
404 => Operation.response("Not Found", "application/json", ApiError)
},
security: [
%{
@ -224,6 +230,7 @@ defmodule Pleroma.Web.ApiSpec.ChatOperation do
ChatMessage
),
400 => Operation.response("Bad Request", "application/json", ApiError),
404 => Operation.response("Not Found", "application/json", ApiError),
422 => Operation.response("MRF Rejection", "application/json", ApiError)
},
security: [
@ -249,7 +256,8 @@ defmodule Pleroma.Web.ApiSpec.ChatOperation do
"The deleted ChatMessage",
"application/json",
ChatMessage
)
),
404 => Operation.response("Not Found", "application/json", ApiError)
},
security: [
%{
@ -268,7 +276,8 @@ defmodule Pleroma.Web.ApiSpec.ChatOperation do
Operation.parameter(:id, :path, :string, "The id of the chat", required: true)
],
responses: %{
200 => Operation.response("The existing chat", "application/json", Chat)
200 => Operation.response("The existing chat", "application/json", Chat),
404 => Operation.response("Not Found", "application/json", ApiError)
},
security: [
%{
@ -287,7 +296,8 @@ defmodule Pleroma.Web.ApiSpec.ChatOperation do
Operation.parameter(:id, :path, :string, "The id of the chat", required: true)
],
responses: %{
200 => Operation.response("The existing chat", "application/json", Chat)
200 => Operation.response("The existing chat", "application/json", Chat),
404 => Operation.response("Not Found", "application/json", ApiError)
},
security: [
%{

View file

@ -41,7 +41,8 @@ defmodule Pleroma.Web.ApiSpec.ListOperation do
responses: %{
200 => Operation.response("List", "application/json", List),
400 => Operation.response("Error", "application/json", ApiError),
404 => Operation.response("Error", "application/json", ApiError)
404 => Operation.response("Error", "application/json", ApiError),
422 => Operation.response("Error", "application/json", ApiError)
}
}
end
@ -175,7 +176,8 @@ defmodule Pleroma.Web.ApiSpec.ListOperation do
exclusive: %Schema{
type: :boolean,
description: "Whether members of the list should be removed from the “Home” feed"
}
},
emoji: %Schema{type: :string, description: "List emoji", nullable: true}
},
required: [:title]
},
@ -194,7 +196,8 @@ defmodule Pleroma.Web.ApiSpec.ListOperation do
exclusive: %Schema{
type: :boolean,
description: "Whether members of the list should be removed from the “Home” feed"
}
},
emoji: %Schema{type: :string, description: "List emoji", nullable: true}
}
},
required: true

View file

@ -0,0 +1,348 @@
# Pleroma: A lightweight social networking server
# Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.ApiSpec.MastodonAdmin.AccountOperation do
alias OpenApiSpex.Operation
alias OpenApiSpex.Schema
alias Pleroma.Web.ApiSpec.Schemas.Account
alias Pleroma.Web.ApiSpec.Schemas.ApiError
alias Pleroma.Web.ApiSpec.Schemas.FlakeID
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 (Mastodon API)"],
summary: "View accounts by criteria (v1)",
operationId: "MastodonAdmin.AccountController.index",
description: "View accounts matching certain criteria for filtering, up to 40 at a time.",
security: [%{"oAuth" => ["admin:read:accounts"]}],
parameters:
[
Operation.parameter(:local, :query, :boolean, "Filter for local accounts?"),
Operation.parameter(:remote, :query, :boolean, "Filter for remote accounts?"),
Operation.parameter(
:active,
:query,
:boolean,
"Filter for currently active accounts?"
),
Operation.parameter(
:pending,
:query,
:boolean,
"Filter for currently pending accounts?"
),
Operation.parameter(
:disabled,
:query,
:boolean,
"Filter for currently disabled accounts?"
),
Operation.parameter(
:silenced,
:query,
:boolean,
"Filter for currently silenced accounts? (not implemented yet)"
),
Operation.parameter(
:suspended,
:query,
:boolean,
"Filter for currently suspended accounts? (not implemented yet)"
),
Operation.parameter(
:sensitized,
:query,
:boolean,
"Filter for accounts force-marked as sensitive? (not implemented yet)"
),
Operation.parameter(:username, :query, :string, "Search for the given username"),
Operation.parameter(
:display_name,
:query,
:string,
"Search for the given display name"
),
Operation.parameter(
:by_domain,
:query,
:string,
"Filter by the given domain"
),
Operation.parameter(:email, :query, :string, "Lookup a user with this email"),
Operation.parameter(
:ip,
:query,
:string,
"Lookup users with this IP address (not implemented yet)"
),
Operation.parameter(:staff, :query, :boolean, "Filter for staff accounts?")
] ++
pagination_params(),
responses: %{
200 =>
Operation.response("Account", "application/json", %Schema{
title: "ArrayOfAccounts",
type: :array,
items: account()
}),
401 => Operation.response("Error", "application/json", ApiError)
}
}
end
def index2_operation do
%Operation{
tags: ["User administration (Mastodon API)"],
summary: "View accounts by criteria (v2)",
operationId: "MastodonAdmin.AccountController.index2",
description: "View accounts matching certain criteria for filtering, up to 40 at a time.",
security: [%{"oAuth" => ["admin:read:accounts"]}],
parameters:
[
Operation.parameter(
:origin,
:query,
%Schema{type: :string, enum: ["local", "remote"]},
"Filter for local or remote accounts"
),
Operation.parameter(
:status,
:query,
%Schema{
type: :string,
enum: ["active", "inactive", "pending", "disabled", "silenced", "suspended"]
},
"Filter for active, pending, disabled, silenced or suspended accounts"
),
Operation.parameter(
:permissions,
:query,
:string,
"Filter for accounts with staff permissions (users that can manage reports)."
),
Operation.parameter(
:role_ids,
:query,
%Schema{
oneOf: [
%Schema{type: :array, items: %Schema{type: :string}},
%Schema{type: :string}
]
},
"Filter for users with these roles. (not implemented yet)"
),
Operation.parameter(
:invited_by,
:query,
:string,
"Lookup users invited by the account with this ID. (not implemented yet)"
),
Operation.parameter(:username, :query, :string, "Search for the given username"),
Operation.parameter(
:display_name,
:query,
:string,
"Search for the given display name"
),
Operation.parameter(
:by_domain,
:query,
:string,
"Filter by the given domain"
),
Operation.parameter(:email, :query, :string, "Lookup a user with this email"),
Operation.parameter(
:ip,
:query,
:string,
"Lookup users with this IP address (not implemented yet)"
)
] ++
pagination_params(),
responses: %{
200 =>
Operation.response("Account", "application/json", %Schema{
title: "ArrayOfAccounts",
type: :array,
items: account()
}),
401 => Operation.response("Error", "application/json", ApiError)
}
}
end
def show_operation do
%Operation{
tags: ["User administration (Mastodon API)"],
summary: "View a specific account",
operationId: "MastodonAdmin.AccountController.show",
description: "View admin-level information about the given account.",
security: [%{"oAuth" => ["admin:read:accounts"]}],
parameters: [
Operation.parameter(:id, :path, :string, "ID of the account")
],
responses: %{
200 => Operation.response("Account", "application/json", account()),
401 => Operation.response("Error", "application/json", ApiError),
404 => Operation.response("Error", "application/json", ApiError)
}
}
end
def account_action_operation do
%Operation{
tags: ["User administration (Mastodon API)"],
summary: "Perform an action against an account",
operationId: "MastodonAdmin.AccountController.account_action",
description:
"Perform an action against an account and log this action in the moderation history.",
security: [%{"oAuth" => ["admin:write:accounts"]}],
parameters: [
Operation.parameter(:id, :path, :string, "ID of the account")
],
requestBody:
request_body(
"Parameters",
%Schema{
type: :object,
properties: %{
type: %Schema{
type: :string,
enum: ["none", "disable"]
},
report_id: %Schema{
type: :string,
nullable: true,
description: "ID of an associated report that caused this action to be taken"
}
},
required: [:type]
},
required: true
),
responses: %{
204 => no_content_response(),
400 => Operation.response("Error", "application/json", ApiError),
401 => Operation.response("Error", "application/json", ApiError),
403 => Operation.response("Error", "application/json", ApiError),
404 => Operation.response("Error", "application/json", ApiError)
}
}
end
def delete_operation do
%Operation{
tags: ["User administration (Mastodon API)"],
summary: "Delete a specific account",
operationId: "MastodonAdmin.AccountController.delete",
description: "Delete the given account.",
security: [%{"oAuth" => ["admin:write:accounts"]}],
parameters: [
Operation.parameter(:id, :path, :string, "ID of the account")
],
responses: %{
200 => Operation.response("Account", "application/json", account()),
401 => Operation.response("Error", "application/json", ApiError),
404 => Operation.response("Error", "application/json", ApiError)
}
}
end
def enable_operation do
%Operation{
tags: ["User administration (Mastodon API)"],
summary: "Re-enable account",
operationId: "MastodonAdmin.AccountController.enable",
description: "Re-enable a local account whose login is currently disabled.",
security: [%{"oAuth" => ["admin:write:accounts"]}],
parameters: [
Operation.parameter(:id, :path, :string, "ID of the account")
],
responses: %{
200 => Operation.response("Account", "application/json", account()),
401 => Operation.response("Error", "application/json", ApiError),
404 => Operation.response("Error", "application/json", ApiError)
}
}
end
def approve_operation do
%Operation{
tags: ["User administration (Mastodon API)"],
summary: "Approve pending account",
operationId: "MastodonAdmin.AccountController.approve",
description: "Approve the given local account if it is currently pending approval.",
parameters: [
Operation.parameter(:id, :path, :string, "ID of the account")
],
responses: %{
200 => Operation.response("Account", "application/json", account()),
401 => Operation.response("Error", "application/json", ApiError),
404 => Operation.response("Error", "application/json", ApiError)
}
}
end
def reject_operation do
%Operation{
tags: ["User administration (Mastodon API)"],
summary: "Reject pending account",
operationId: "MastodonAdmin.AccountController.reject",
description: "Reject the given local account if it is currently pending approval.",
parameters: [
Operation.parameter(:id, :path, :string, "ID of the account")
],
responses: %{
200 => Operation.response("Account", "application/json", account()),
400 => Operation.response("Error", "application/json", ApiError),
401 => Operation.response("Error", "application/json", ApiError),
404 => Operation.response("Error", "application/json", ApiError)
}
}
end
def account do
%Schema{
title: "Admin::Account",
description: "Admin-level information about a given account.",
type: :object,
properties: %{
id: FlakeID,
username: %Schema{type: :string},
domain: %Schema{type: :string, nullable: true},
created_at: %Schema{type: :string, format: "date-time"},
email: %Schema{type: :string, format: "email", nullable: true},
ip: %Schema{type: :string, nullable: true},
ips: %Schema{
type: :array,
items: %Schema{
type: :object,
properties: %{
ip: %Schema{type: :string},
used_at: %Schema{type: :string, format: "date-time"}
}
}
},
locale: %Schema{type: :string, nullable: true},
invite_request: %Schema{type: :string, nullable: true},
role: %Schema{type: :string, nullable: true},
confirmed: %Schema{type: :boolean},
approved: %Schema{type: :boolean},
disabled: %Schema{type: :boolean},
silenced: %Schema{type: :boolean, nullable: true},
suspended: %Schema{type: :boolean, nullable: true},
account: Account,
created_by_application_id: %Schema{type: :string, nullable: true},
invited_by_account_id: %Schema{type: :string, nullable: true}
}
}
end
end

View file

@ -0,0 +1,180 @@
# Pleroma: A lightweight social networking server
# Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.ApiSpec.MastodonAdmin.ReportOperation do
alias OpenApiSpex.Operation
alias OpenApiSpex.Schema
alias Pleroma.Web.ApiSpec.MastodonAdmin.AccountOperation
alias Pleroma.Web.ApiSpec.Schemas.ApiError
alias Pleroma.Web.ApiSpec.Schemas.FlakeID
alias Pleroma.Web.ApiSpec.Schemas.Status
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: ["Report management (Mastodon API)"],
summary: "View all reports",
operationId: "MastodonAdmin.ReportController.index",
description:
"View all reports. Pagination may be done with HTTP Link header in the response.",
security: [%{"oAuth" => ["admin:read:reports"]}],
parameters:
[
Operation.parameter(:resolved, :query, :boolean, "Filter for resolved reports"),
Operation.parameter(:unresolved, :query, :boolean, "Filter for open reports"),
Operation.parameter(:account_id, :query, :string, "Filter by author account id"),
Operation.parameter(
:target_account_id,
:query,
:string,
"Filter by report target account id"
)
] ++
pagination_params(),
responses: %{
200 =>
Operation.response("Reports", "application/json", %Schema{
title: "ArrayOfReports",
type: :array,
items: report()
}),
401 => Operation.response("Error", "application/json", ApiError)
}
}
end
def show_operation do
%Operation{
tags: ["Report management (Mastodon API)"],
summary: "View a single report",
operationId: "MastodonAdmin.ReportController.show",
description: "View information about the report with the given ID.",
security: [%{"oAuth" => ["admin:read:reports"]}],
parameters: [
Operation.parameter(:id, :path, :string, "ID of the report")
],
responses: %{
200 => Operation.response("Report", "application/json", report()),
401 => Operation.response("Error", "application/json", ApiError),
404 => Operation.response("Error", "application/json", ApiError)
}
}
end
def resolve_operation do
%Operation{
tags: ["Report management (Mastodon API)"],
summary: "Mark as resolved",
operationId: "MastodonAdmin.ReportController.resolve",
description: "Mark a report as resolved with no further action taken.",
security: [%{"oAuth" => ["admin:write:reports"]}],
parameters: [
Operation.parameter(:id, :path, :string, "ID of the report")
],
responses: %{
200 => Operation.response("Report", "application/json", report()),
400 => Operation.response("Error", "application/json", ApiError),
401 => Operation.response("Error", "application/json", ApiError),
404 => Operation.response("Error", "application/json", ApiError)
}
}
end
def reopen_operation do
%Operation{
tags: ["Report management (Mastodon API)"],
summary: "Re-open report",
operationId: "MastodonAdmin.ReportController.reopen",
description: "Reopen a currently closed report.",
security: [%{"oAuth" => ["admin:write:reports"]}],
parameters: [
Operation.parameter(:id, :path, :string, "ID of the report")
],
responses: %{
200 => Operation.response("Report", "application/json", report()),
400 => Operation.response("Error", "application/json", ApiError),
401 => Operation.response("Error", "application/json", ApiError),
404 => Operation.response("Error", "application/json", ApiError)
}
}
end
def assign_to_self_operation do
%Operation{
tags: ["Report management (Mastodon API)"],
summary: "Assign report to self",
operationId: "MastodonAdmin.ReportController.assign_to_self",
security: [%{"oAuth" => ["admin:write:reports"]}],
parameters: [Operation.parameter(:id, :path, :string, "ID of the report")],
responses: report_update_responses()
}
end
def unassign_operation do
%Operation{
tags: ["Report management (Mastodon API)"],
summary: "Unassign report",
operationId: "MastodonAdmin.ReportController.unassign",
security: [%{"oAuth" => ["admin:write:reports"]}],
parameters: [Operation.parameter(:id, :path, :string, "ID of the report")],
responses: report_update_responses()
}
end
defp report_update_responses do
%{
200 => Operation.response("Report", "application/json", report()),
400 => Operation.response("Error", "application/json", ApiError),
401 => Operation.response("Error", "application/json", ApiError),
404 => Operation.response("Error", "application/json", ApiError)
}
end
defp report do
%Schema{
title: "Admin::Report",
type: :object,
properties: %{
id: FlakeID,
action_taken: %Schema{type: :boolean},
action_taken_at: %Schema{type: :string, format: "date-time", nullable: true},
category: %Schema{type: :string, enum: ["spam", "legal", "violation", "other"]},
comment: %Schema{type: :string, nullable: true},
forwarded: %Schema{type: :boolean, nullable: true},
created_at: %Schema{type: :string, format: "date-time"},
updated_at: %Schema{type: :string, format: "date-time"},
account: AccountOperation.account(),
target_account: AccountOperation.account(),
assigned_account: %Schema{
oneOf: [AccountOperation.account()],
nullable: true
},
action_taken_by_account: %Schema{
oneOf: [AccountOperation.account()],
nullable: true
},
statuses: %Schema{
type: :array,
items: Status
},
rules: %Schema{
type: :array,
items: %Schema{
type: :object,
properties: %{
id: %Schema{type: :string},
text: %Schema{type: :string}
}
}
}
}
}
end
end

View file

@ -90,6 +90,79 @@ defmodule Pleroma.Web.ApiSpec.NotificationOperation do
}
end
def grouped_index_operation do
%Operation{
tags: ["Notifications"],
summary: "Retrieve grouped notifications",
description: "Notifications concerning the user, grouped by supported notification types.",
operationId: "NotificationController.grouped_index",
security: [%{"oAuth" => ["read:notifications"]}],
parameters: grouped_notification_params() ++ pagination_params(),
responses: %{
200 => Operation.response("Grouped notifications", "application/json", grouped_result()),
404 => Operation.response("Error", "application/json", ApiError)
}
}
end
def show_group_operation do
%Operation{
tags: ["Notifications"],
summary: "Retrieve a notification group",
operationId: "NotificationController.show_group",
security: [%{"oAuth" => ["read:notifications"]}],
parameters: [group_key_param()],
responses: %{
200 => Operation.response("Grouped notifications", "application/json", grouped_result()),
404 => Operation.response("Error", "application/json", ApiError)
}
}
end
def group_accounts_operation do
%Operation{
tags: ["Notifications"],
summary: "Retrieve notification group accounts",
operationId: "NotificationController.group_accounts",
security: [%{"oAuth" => ["read:notifications"]}],
parameters: [group_key_param()],
responses: %{
200 =>
Operation.response("Accounts", "application/json", %Schema{
type: :array,
items: Account
})
}
}
end
def unread_count_operation do
%Operation{
tags: ["Notifications"],
summary: "Retrieve unread grouped notification count",
operationId: "NotificationController.unread_count",
security: [%{"oAuth" => ["read:notifications"]}],
parameters:
grouped_notification_params() ++
[
Operation.parameter(
:limit,
:query,
%Schema{type: :integer},
"Maximum number of notifications to count"
)
],
responses: %{
200 =>
Operation.response("Unread notification group count", "application/json", %Schema{
type: :object,
properties: %{count: %Schema{type: :integer}}
}),
404 => Operation.response("Error", "application/json", ApiError)
}
}
end
def clear_operation do
%Operation{
tags: ["Notifications"],
@ -113,6 +186,18 @@ defmodule Pleroma.Web.ApiSpec.NotificationOperation do
}
end
def dismiss_group_operation do
%Operation{
tags: ["Notifications"],
summary: "Dismiss a notification group",
description: "Clear all notifications in a notification group from the server.",
operationId: "NotificationController.dismiss_group",
parameters: [group_key_param()],
security: [%{"oAuth" => ["write:notifications"]}],
responses: %{200 => empty_object_response()}
}
end
def dismiss_via_body_operation do
%Operation{
tags: ["Notifications"],
@ -183,7 +268,7 @@ defmodule Pleroma.Web.ApiSpec.NotificationOperation do
},
example: %{
"id" => "34975861",
"group-key" => "ungrouped-34975861",
"group_key" => "ungrouped-34975861",
"type" => "mention",
"created_at" => "2019-11-23T07:49:02.064Z",
"account" => Account.schema().example,
@ -193,6 +278,73 @@ defmodule Pleroma.Web.ApiSpec.NotificationOperation do
}
end
defp grouped_result do
%Schema{
title: "GroupedNotificationsResults",
type: :object,
properties: %{
accounts: %Schema{type: :array, items: Account},
statuses: %Schema{type: :array, items: Status},
notification_groups: %Schema{type: :array, items: notification_group()}
},
required: [:accounts, :statuses, :notification_groups]
}
end
defp notification_group do
%Schema{
title: "NotificationGroup",
type: :object,
properties: %{
group_key: %Schema{type: :string},
notifications_count: %Schema{type: :integer},
type: notification_type(),
most_recent_notification_id: %Schema{type: :string},
page_min_id: %Schema{type: :string, nullable: true},
page_max_id: %Schema{type: :string, nullable: true},
latest_page_notification_at: %Schema{type: :string, format: :"date-time", nullable: true},
sample_account_ids: %Schema{type: :array, items: %Schema{type: :string}},
status_id: %Schema{type: :string, nullable: true}
},
required: [
:group_key,
:notifications_count,
:type,
:most_recent_notification_id,
:sample_account_ids
]
}
end
defp grouped_notification_params do
[
Operation.parameter(
:exclude_types,
:query,
%Schema{type: :array, items: notification_type()},
"Array of types to exclude"
),
Operation.parameter(
:account_id,
:query,
%Schema{type: :string},
"Return only notifications received from this account"
),
Operation.parameter(
:types,
:query,
%Schema{type: :array, items: notification_type()},
"Include the notifications for activities with the given types"
),
Operation.parameter(
:grouped_types,
:query,
%Schema{type: :array, items: notification_type()},
"Notification types that may be grouped"
)
]
end
defp notification_type do
%Schema{
type: :string,
@ -238,4 +390,11 @@ defmodule Pleroma.Web.ApiSpec.NotificationOperation do
required: true
)
end
defp group_key_param do
Operation.parameter(:group_key, :path, :string, "Notification group key",
example: "favourite-123",
required: true
)
end
end

View file

@ -356,34 +356,6 @@ defmodule Pleroma.Web.ApiSpec.StatusOperation do
}
end
def card_operation do
%Operation{
tags: ["Retrieve status information"],
deprecated: true,
summary: "Preview card",
description: "Deprecated in favor of card property inlined on Status entity",
operationId: "StatusController.card",
parameters: [id_param()],
security: [%{"oAuth" => ["read:statuses"]}],
responses: %{
200 =>
Operation.response("Card", "application/json", %Schema{
type: :object,
nullable: true,
properties: %{
type: %Schema{type: :string, enum: ["link", "photo", "video", "rich"]},
provider_name: %Schema{type: :string, nullable: true},
provider_url: %Schema{type: :string, format: :uri},
url: %Schema{type: :string, format: :uri},
image: %Schema{type: :string, nullable: true, format: :uri},
title: %Schema{type: :string},
description: %Schema{type: :string}
}
})
}
}
end
def favourited_by_operation do
%Operation{
tags: ["Retrieve status information"],

View file

@ -5,6 +5,7 @@
defmodule Pleroma.Web.ApiSpec.Schemas.ChatMessage do
alias OpenApiSpex.Schema
alias Pleroma.Web.ApiSpec.Schemas.Emoji
alias Pleroma.Web.ApiSpec.Schemas.PreviewCard
require OpenApiSpex
@ -22,36 +23,8 @@ defmodule Pleroma.Web.ApiSpec.Schemas.ChatMessage do
emojis: %Schema{type: :array, items: Emoji},
attachment: %Schema{type: :object, nullable: true},
card: %Schema{
type: :object,
nullable: true,
description: "Preview card for links included within status content",
required: [:url, :title, :description, :type],
properties: %{
type: %Schema{
type: :string,
enum: ["link", "photo", "video", "rich"],
description: "The type of the preview card"
},
provider_name: %Schema{
type: :string,
nullable: true,
description: "The provider of the original resource"
},
provider_url: %Schema{
type: :string,
format: :uri,
description: "A link to the provider of the original resource"
},
url: %Schema{type: :string, format: :uri, description: "Location of linked resource"},
image: %Schema{
type: :string,
nullable: true,
format: :uri,
description: "Preview thumbnail"
},
title: %Schema{type: :string, description: "Title of linked resource"},
description: %Schema{type: :string, description: "Description of preview"}
}
allOf: [PreviewCard],
nullable: true
},
unread: %Schema{type: :boolean, description: "Whether a message has been marked as read."}
},

View file

@ -17,11 +17,26 @@ defmodule Pleroma.Web.ApiSpec.Schemas.List do
exclusive: %Schema{
type: :boolean,
description: "Whether members of the list should be removed from the “Home” feed"
},
pleroma: %Schema{
type: :object,
properties: %{
emoji: %Schema{type: :string, description: "List emoji", nullable: true},
emoji_url: %Schema{
type: :string,
description: "URL of the list emoji if it's a custom emoji, null otherwise",
nullable: true
}
}
}
},
example: %{
"id" => "12249",
"title" => "Friends"
"title" => "Friends",
"pleroma" => %{
"emoji" => nil,
"emoji_url" => nil
}
}
})
end

View file

@ -0,0 +1,109 @@
# Pleroma: A lightweight social networking server
# Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.ApiSpec.Schemas.PreviewCard do
alias OpenApiSpex.Schema
alias Pleroma.Web.ApiSpec.Schemas.Account
require OpenApiSpex
OpenApiSpex.schema(%{
title: "PreviewCard",
description: "Preview card for a link included within status or chat message content",
type: :object,
required: [
:url,
:title,
:description,
:language,
:type,
:authors,
:author_name,
:author_url,
:provider_name,
:provider_url,
:html,
:width,
:height,
:image,
:image_description,
:embed_url,
:blurhash,
:published_at
],
properties: %{
url: %Schema{type: :string, format: :uri, description: "Location of linked resource"},
title: %Schema{type: :string, description: "Title of linked resource"},
description: %Schema{type: :string, description: "Description of preview"},
language: %Schema{
type: :string,
nullable: true,
description: "Language of the linked resource"
},
type: %Schema{
type: :string,
enum: ["link", "photo", "video", "rich"],
description: "The type of the preview card"
},
authors: %Schema{
type: :array,
description: "Fediverse accounts of the authors of the original resource",
items: %Schema{
type: :object,
required: [:name, :url, :account],
properties: %{
name: %Schema{type: :string},
url: %Schema{type: :string},
account: %Schema{allOf: [Account], nullable: true}
}
}
},
author_name: %Schema{type: :string, description: "Author of the original resource"},
author_url: %Schema{
type: :string,
description: "Link to the author of the original resource"
},
provider_name: %Schema{
type: :string,
description: "The provider of the original resource"
},
provider_url: %Schema{
type: :string,
description: "A link to the provider of the original resource"
},
html: %Schema{
type: :string,
format: :html,
description: "HTML to be used for generating the preview card"
},
width: %Schema{type: :integer, description: "Width of preview, in pixels"},
height: %Schema{type: :integer, description: "Height of preview, in pixels"},
image: %Schema{
type: :string,
nullable: true,
format: :uri,
description: "Preview thumbnail"
},
image_description: %Schema{
type: :string,
description: "Alternate text that describes what is in the thumbnail"
},
embed_url: %Schema{
type: :string,
description: "Used for photo embeds, instead of custom `html`"
},
blurhash: %Schema{
type: :string,
nullable: true,
description:
"A hash computed by the [BlurHash algorithm](https://github.com/woltapp/blurhash), for generating colorful preview thumbnails when media has not been downloaded yet."
},
published_at: %Schema{
type: :string,
nullable: true,
description: "Publication date of the linked resource"
}
}
})
end

View file

@ -9,6 +9,7 @@ defmodule Pleroma.Web.ApiSpec.Schemas.Status do
alias Pleroma.Web.ApiSpec.Schemas.Emoji
alias Pleroma.Web.ApiSpec.Schemas.FlakeID
alias Pleroma.Web.ApiSpec.Schemas.Poll
alias Pleroma.Web.ApiSpec.Schemas.PreviewCard
alias Pleroma.Web.ApiSpec.Schemas.Tag
alias Pleroma.Web.ApiSpec.Schemas.VisibilityScope
@ -31,40 +32,8 @@ defmodule Pleroma.Web.ApiSpec.Schemas.Status do
},
bookmarked: %Schema{type: :boolean, description: "Have you bookmarked this status?"},
card: %Schema{
type: :object,
nullable: true,
description: "Preview card for links included within status content",
required: [:url, :title, :description, :type],
properties: %{
type: %Schema{
type: :string,
enum: ["link", "photo", "video", "rich"],
description: "The type of the preview card"
},
provider_name: %Schema{
type: :string,
nullable: true,
description: "The provider of the original resource"
},
provider_url: %Schema{
type: :string,
format: :uri,
description: "A link to the provider of the original resource"
},
url: %Schema{type: :string, format: :uri, description: "Location of linked resource"},
image: %Schema{
type: :string,
nullable: true,
format: :uri,
description: "Preview thumbnail"
},
image_description: %Schema{
type: :string,
description: "Alternate text that describes what is in the thumbnail"
},
title: %Schema{type: :string, description: "Title of linked resource"},
description: %Schema{type: :string, description: "Description of preview"}
}
allOf: [PreviewCard],
nullable: true
},
content: %Schema{type: :string, format: :html, description: "HTML-encoded status content"},
text: %Schema{

View file

@ -700,7 +700,7 @@ defmodule Pleroma.Web.CommonAPI do
end
def update_report_state(activity_id, state) do
with %Activity{} = activity <- Activity.get_by_id(activity_id, filter: []) do
with %Activity{} = activity <- Activity.get_report(activity_id) do
Utils.update_report_state(activity, state)
else
nil -> {:error, :not_found}
@ -715,7 +715,7 @@ defmodule Pleroma.Web.CommonAPI do
end
def assign_report_to_account(activity_id, user) do
with %Activity{} = activity <- Activity.get_by_id(activity_id) do
with %Activity{} = activity <- Activity.get_report(activity_id) do
Utils.assign_report_to_account(activity, user)
else
nil -> {:error, :not_found}

View file

@ -55,16 +55,28 @@ defmodule Pleroma.Web.ControllerHelper do
# TODO: Only fetch the params from open_api_spex when everything is converted
@id_keys Pagination.page_keys() -- ["limit", "order"]
@id_key_atoms Enum.map(@id_keys, &String.to_atom/1)
@drop_id_params_key :drop_id_params
defp build_pagination_fields(conn, min_id, max_id, extra_params, order) do
drop_id_params? = Map.get(extra_params, @drop_id_params_key, false)
extra_params = Map.delete(extra_params, @drop_id_params_key)
path_param_keys =
conn.path_params
|> Map.keys()
|> Enum.flat_map(&[&1, String.to_existing_atom(&1)])
params =
if Map.has_key?(conn.private, :open_api_spex) do
get_in(conn, [Access.key(:private), Access.key(:open_api_spex), Access.key(:params)])
else
conn.params
end
|> Map.drop(Map.keys(conn.path_params) |> Enum.map(&String.to_existing_atom/1))
|> Map.drop(path_param_keys)
|> Map.merge(extra_params)
|> Map.drop(@id_keys)
# Some OpenApiSpex routes cast cursor params to atoms. Keep the historical default for
# existing endpoints, but allow grouped notifications to opt out of stale request cursors.
|> Map.drop(@id_keys ++ if(drop_id_params?, do: @id_key_atoms, else: []))
{{next_id, nid}, {prev_id, pid}} =
if order == :desc,

View file

@ -139,6 +139,8 @@ defmodule Pleroma.Web.Endpoint do
from: {:pleroma, "priv/static/adminfe/"}
)
plug(Pleroma.Web.Plugs.StaticNotFoundPlug)
# Code reloading can be explicitly enabled under the
# :code_reloader configuration of your endpoint.
if code_reloading? do

View file

@ -89,7 +89,8 @@ defmodule Pleroma.Web.Federator do
# Job Worker Callbacks
@spec perform(atom(), any()) :: {:ok, any()} | {:error, any()}
@impl true
@spec perform(atom(), any()) :: :ok | {:ok, any()} | {:error, any()}
def perform(:publish_one, params) do
Publisher.prepare_one(params)
|> Publisher.publish_one()

View file

@ -3,5 +3,6 @@
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.Federator.Publishing do
@callback perform(atom(), any()) :: :ok | {:ok, any()} | {:error, any()}
@callback publish(map()) :: any()
end

View file

@ -38,6 +38,20 @@ defmodule Pleroma.Web.Feed.FeedView do
end
end
def most_recent_update([], :rss), do: nil
def most_recent_update(activities, :rss) do
activities
|> Enum.map(fn activity ->
case activity.object do
%Object{updated_at: updated_at} -> updated_at
_ -> activity.updated_at
end
end)
|> Enum.max_by(&NaiveDateTime.to_erl/1)
|> to_rfc2822()
end
def most_recent_update(activities, user, :atom) do
(List.first(activities) || user).updated_at
|> to_rfc3339()
@ -97,6 +111,67 @@ defmodule Pleroma.Web.Feed.FeedView do
end
end
def rss_content_encoded(data) do
data
|> feed_content_encoded()
|> String.replace("]]>", "]]&gt;")
end
def atom_content_encoded(data), do: feed_content_encoded(data)
defp feed_content_encoded(data) do
base_content =
case activity_content(data) do
"" ->
(data["summary"] || data["type"] || "")
|> escape()
content ->
content
end
attachments_html =
if sensitive?(data) do
""
else
(data["attachment"] || [])
|> Enum.map(&rss_attachment_preview/1)
|> Enum.reject(&(&1 == ""))
|> Enum.join("<br/><br/>")
end
[base_content, attachments_html]
|> Enum.reject(&(&1 == ""))
|> Enum.join("<br/><br/>")
end
defp rss_attachment_preview(attachment) do
href = attachment_href(attachment)
if is_binary(href) and href != "" do
media_type = attachment_type(attachment) || "application/octet-stream"
escaped_href = escape(href)
name = attachment["name"] || "Attachment"
escaped_name = escape(name)
cond do
String.starts_with?(media_type, "image/") ->
~s(<p><img src="#{escaped_href}" alt="#{escaped_name}" loading="lazy"/></p>)
String.starts_with?(media_type, "video/") ->
~s(<p><video controls preload="metadata" src="#{escaped_href}"></video></p><p><a href="#{escaped_href}">#{escaped_name}</a></p>)
String.starts_with?(media_type, "audio/") ->
~s(<p><audio controls preload="metadata" src="#{escaped_href}"></audio></p><p><a href="#{escaped_href}">#{escaped_name}</a></p>)
true ->
~s(<p><a href="#{escaped_href}">#{escaped_name}</a></p>)
end
else
""
end
end
def activity_content(%{"content" => content}) do
content
|> String.replace(~r/[\n\r]/, "")
@ -106,16 +181,104 @@ defmodule Pleroma.Web.Feed.FeedView do
def activity_context(activity), do: escape(activity.data["context"])
def sensitive?(data), do: data["sensitive"] in [true, "true"]
def feed_self_url(conn) do
conn
|> Phoenix.Controller.current_url()
|> escape()
end
def activity_link(activity, data) do
cond do
activity.local -> data["id"] || data["url"]
true -> data["external_url"] || data["id"] || data["url"]
end
end
def attachment_href(attachment) do
attachment["url"]
|> hd()
attachment
|> attachment_url_data()
|> Map.get("href")
end
def attachment_type(attachment) do
attachment["url"]
|> hd()
|> Map.get("mediaType")
attachment
|> attachment_url_data()
|> Map.get("mediaType") || attachment["mediaType"]
end
def attachment_size(attachment) do
attachment
|> attachment_url_data()
|> Map.get("size", 0)
end
def attachment_size_positive(attachment) do
case attachment_size(attachment) do
size when is_integer(size) and size > 0 ->
size
size when is_binary(size) ->
case Integer.parse(size) do
{parsed, ""} when parsed > 0 -> parsed
_ -> nil
end
_ ->
nil
end
end
def attachment_medium(attachment) do
case attachment_type(attachment) do
"image/" <> _rest -> "image"
"video/" <> _rest -> "video"
"audio/" <> _rest -> "audio"
_ -> "document"
end
end
def rss_enclosure_attachment(attachments) do
Enum.find(attachments || [], &(not is_nil(attachment_size_positive(&1))))
end
def attachment_description(attachment) do
attachment["name"] || ""
end
def media_content_xml(_attachment, sensitive) when sensitive in [true, "true"], do: ""
def media_content_xml(attachment, _sensitive) do
href = escape(attachment_href(attachment) || "")
type = escape(attachment_type(attachment) || "application/octet-stream")
medium = escape(attachment_medium(attachment))
file_size_attr =
case attachment_size_positive(attachment) do
size when is_integer(size) -> ~s( fileSize="#{size}")
_ -> ""
end
case attachment_description(attachment) do
"" ->
~s(<media:content url="#{href}" type="#{type}"#{file_size_attr} medium="#{medium}"/>\n)
description ->
"""
<media:content url="#{href}" type="#{type}"#{file_size_attr} medium="#{medium}">
<media:description type="plain">#{escape(description)}</media:description>
</media:content>
"""
end
end
defp attachment_url_data(attachment) do
case attachment["url"] do
[first | _] when is_map(first) -> first
%{} = map -> map
_ -> %{}
end
end
def get_href(id) do

View file

@ -0,0 +1,305 @@
# Pleroma: A lightweight social networking server
# Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.MastodonAPI.Admin.AccountController do
use Pleroma.Web, :controller
import Pleroma.Web.ControllerHelper,
only: [
add_link_headers: 2,
assign_account_by_id: 2,
json_response: 3
]
alias Pleroma.Activity
alias Pleroma.ModerationLog
alias Pleroma.Pagination
alias Pleroma.User
alias Pleroma.Web.ActivityPub.Builder
alias Pleroma.Web.ActivityPub.Pipeline
alias Pleroma.Web.CommonAPI
alias Pleroma.Web.Plugs.OAuthScopesPlug
@filter_params ~W(
local external active needing_approval deactivated nickname name domain email staff origin status
)
plug(Pleroma.Web.ApiSpec.CastAndValidate)
plug(
OAuthScopesPlug,
%{scopes: ["admin:read:accounts"]}
when action in [:index, :index2, :show]
)
action_fallback(Pleroma.Web.MastodonAPI.FallbackController)
plug(
OAuthScopesPlug,
%{scopes: ["admin:write:accounts"]}
when action in [
:delete,
:enable,
:account_action,
:approve,
:reject
]
)
plug(
:assign_account_by_id
when action in [
:show,
:delete,
:enable,
:account_action,
:approve,
:reject
]
)
defdelegate open_api_operation(action), to: Pleroma.Web.ApiSpec.MastodonAdmin.AccountOperation
def index(conn, params) do
users =
params
|> build_criteria()
|> User.Query.build()
|> Pagination.fetch_paginated(params)
conn
|> add_link_headers(users)
|> render("index.json", users: users)
end
def index2(conn, params) do
users =
params
|> build_criteria_v2()
|> User.Query.build()
|> Pagination.fetch_paginated(params)
conn
|> add_link_headers(users)
|> render("index.json", users: users)
end
def show(%{assigns: %{user: _admin, account: user}} = conn, _params) do
render(conn, "show.json", user: user)
end
def account_action(
%{assigns: %{user: admin, account: user}, body_params: %{type: type} = body_params} =
conn,
_params
) do
with :ok <- validate_account_action(user, type),
{:ok, report} <- associated_report(user, body_params),
:ok <- resolve_report(admin, report),
{:ok, _user} <- handle_account_action(user, admin, type) do
json_response(conn, :no_content, "")
else
{:error, :not_found} ->
{:error, :not_found}
{:error, error} ->
json_response(conn, :bad_request, %{error: error})
end
end
def delete(%{assigns: %{user: admin, account: user}} = conn, _params) do
{:ok, delete_data, _} = Builder.delete(admin, user.ap_id)
Pipeline.common_pipeline(delete_data, local: true)
ModerationLog.insert_log(%{
actor: admin,
subject: [user],
action: "delete"
})
render(conn, "show.json", user: user)
end
def enable(%{assigns: %{user: admin, account: user}} = conn, _params) do
{:ok, user} = User.set_activation(user, true)
ModerationLog.insert_log(%{
actor: admin,
subject: [user],
action: "activate"
})
render(conn, "show.json", user: user)
end
def approve(%{assigns: %{user: admin, account: user}} = conn, _params) do
{:ok, user} = User.approve(user)
ModerationLog.insert_log(%{
actor: admin,
subject: [user],
action: "approve"
})
render(conn, "show.json", user: user)
end
def reject(%{assigns: %{user: admin, account: user}} = conn, _params) do
with {:ok, _} <- User.reject(user) do
ModerationLog.insert_log(%{
actor: admin,
subject: [user],
action: "reject"
})
render(conn, "show.json", user: user)
else
{:error, error} ->
json_response(conn, :bad_request, %{error: error})
end
end
defp handle_account_action(%User{local: true} = user, admin, "disable") do
ModerationLog.insert_log(%{
actor: admin,
subject: [user],
action: "deactivate"
})
User.set_activation(user, false)
end
defp handle_account_action(%User{}, _admin, "disable") do
{:error, "Only local accounts can be disabled"}
end
defp handle_account_action(user, _admin, "none") do
{:ok, user}
end
defp validate_account_action(%User{local: true}, "disable"), do: :ok
defp validate_account_action(%User{}, "disable"),
do: {:error, "Only local accounts can be disabled"}
defp validate_account_action(%User{}, "none"), do: :ok
defp build_criteria(params) do
%{}
|> maybe_filter_local(params)
|> maybe_filter_external(params)
|> maybe_filter_active(params)
|> maybe_filter_needing_approval(params)
|> maybe_filter_deactivated(params)
|> maybe_filter_nickname(params)
|> maybe_filter_name(params)
|> maybe_filter_domain(params)
|> maybe_filter_email(params)
|> maybe_filter_staff(params)
end
defp build_criteria_v2(params) do
%{}
|> maybe_filter_origin(params)
|> maybe_filter_status(params)
|> maybe_filter_staff(params)
|> maybe_filter_nickname(params)
|> maybe_filter_name(params)
|> maybe_filter_domain(params)
|> maybe_filter_email(params)
end
defp maybe_filter_local(criteria, %{local: true} = _params),
do: Map.put(criteria, :local, true)
defp maybe_filter_local(criteria, %{local: false} = _params),
do: Map.put(criteria, :external, true)
defp maybe_filter_external(criteria, %{remote: true} = _params),
do: Map.put(criteria, :external, true)
defp maybe_filter_external(criteria, %{remote: false} = _params),
do: Map.put(criteria, :local, true)
defp maybe_filter_origin(criteria, %{origin: "local"} = _params),
do: Map.put(criteria, :local, true)
defp maybe_filter_origin(criteria, %{origin: "remote"} = _params),
do: Map.put(criteria, :external, true)
defp maybe_filter_active(criteria, %{active: active} = _params),
do: Map.put(criteria, :active, active)
defp maybe_filter_needing_approval(criteria, %{pending: need_approval} = _params),
do: Map.put(criteria, :need_approval, need_approval)
defp maybe_filter_deactivated(criteria, %{disabled: deactivated} = _params),
do: Map.put(criteria, :deactivated, deactivated)
defp maybe_filter_status(criteria, %{status: "active"} = _params),
do: Map.put(criteria, :active, true)
defp maybe_filter_status(criteria, %{status: "inactive"} = _params),
do: Map.put(criteria, :active, false)
defp maybe_filter_status(criteria, %{status: "pending"} = _params),
do: Map.put(criteria, :need_approval, true)
defp maybe_filter_status(criteria, %{status: "disabled"} = _params),
do: Map.put(criteria, :deactivated, true)
defp maybe_filter_nickname(criteria, %{username: nickname} = _params),
do: Map.put(criteria, :nickname, nickname)
defp maybe_filter_name(criteria, %{display_name: name} = _params),
do: Map.put(criteria, :name, name)
defp maybe_filter_domain(criteria, %{by_domain: domain} = _params),
do: Map.put(criteria, :domain, domain)
defp maybe_filter_email(criteria, %{email: email} = _params),
do: Map.put(criteria, :email, email)
defp maybe_filter_staff(criteria, %{permissions: "staff"} = _params),
do: Map.put(criteria, :staff, true)
defp maybe_filter_staff(criteria, %{staff: staff} = _params),
do: Map.put(criteria, :staff, staff)
for filter_param <- @filter_params do
defp unquote(:"maybe_filter_#{filter_param}")(criteria, _params), do: criteria
end
defp associated_report(user, %{report_id: id}) do
case Activity.get_report(id) do
%Activity{data: %{"object" => [target_ap_id | _]}} = report
when target_ap_id == user.ap_id ->
{:ok, report}
%Activity{} ->
{:error, "Report does not target this account"}
nil ->
{:error, :not_found}
end
end
defp associated_report(_user, _params), do: {:ok, nil}
defp resolve_report(admin, %Activity{id: id}) do
with {:ok, activity} <- CommonAPI.update_report_state(id, "resolved"),
report <- Activity.get_by_id_with_user_actor(activity.id) do
ModerationLog.insert_log(%{
action: "report_update",
actor: admin,
subject: activity,
subject_actor: report.user_actor
})
:ok
end
end
defp resolve_report(_admin, nil), do: :ok
end

View file

@ -0,0 +1,171 @@
# Pleroma: A lightweight social networking server
# Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.MastodonAPI.Admin.ReportController do
use Pleroma.Web, :controller
import Pleroma.Web.ControllerHelper,
only: [
add_link_headers: 2,
json_response: 3
]
alias Pleroma.Activity
alias Pleroma.ModerationLog
alias Pleroma.Pagination
alias Pleroma.User
alias Pleroma.Web.ActivityPub.ActivityPub
alias Pleroma.Web.AdminAPI.Report
alias Pleroma.Web.CommonAPI
alias Pleroma.Web.Plugs.OAuthScopesPlug
plug(Pleroma.Web.ApiSpec.CastAndValidate)
plug(OAuthScopesPlug, %{scopes: ["admin:read:reports"]} when action in [:index, :show])
plug(OAuthScopesPlug, %{scopes: ["admin:write:reports"]} when action in [:resolve, :reopen])
plug(
OAuthScopesPlug,
%{scopes: ["admin:write:reports"]} when action in [:assign_to_self, :unassign]
)
action_fallback(Pleroma.Web.MastodonAPI.FallbackController)
defdelegate open_api_operation(action), to: Pleroma.Web.ApiSpec.MastodonAdmin.ReportOperation
def index(conn, params) do
opts =
%{}
|> Map.put(:type, "Flag")
|> Map.put(:skip_preload, true)
|> Map.put(:preload_report_notes, true)
|> Map.put(:total, true)
|> restrict_state(params)
|> restrict_actor(params)
|> restrict_target(params)
reports =
ActivityPub.fetch_activities_query([], opts)
|> Pagination.fetch_paginated(params)
conn
|> add_link_headers(reports)
|> render("index.json", reports: reports)
end
def show(conn, %{id: id}) do
with %Activity{} = report <- Activity.get_report(id) do
render(conn, "show.json", Report.extract_report_info(report))
else
_ -> {:error, :not_found}
end
end
def resolve(%{assigns: %{user: admin}} = conn, %{id: id}) do
with {:ok, activity} <- CommonAPI.update_report_state(id, "resolved"),
report <- Activity.get_by_id_with_user_actor(activity.id) do
ModerationLog.insert_log(%{
action: "report_update",
actor: admin,
subject: activity,
subject_actor: report.user_actor
})
render(conn, "show.json", Report.extract_report_info(report))
else
{:error, :not_found} ->
{:error, :not_found}
{:error, error} ->
json_response(conn, :bad_request, %{error: error})
end
end
def reopen(%{assigns: %{user: admin}} = conn, %{id: id}) do
with {:ok, activity} <- CommonAPI.update_report_state(id, "open"),
report <- Activity.get_by_id_with_user_actor(activity.id) do
ModerationLog.insert_log(%{
action: "report_update",
actor: admin,
subject: activity,
subject_actor: report.user_actor
})
render(conn, "show.json", Report.extract_report_info(report))
else
{:error, :not_found} ->
{:error, :not_found}
{:error, error} ->
json_response(conn, :bad_request, %{error: error})
end
end
def assign_to_self(%{assigns: %{user: admin}} = conn, %{id: id}) do
with {:ok, activity} <- CommonAPI.assign_report_to_account(id, admin.id),
report <- Activity.get_by_id_with_user_actor(activity.id) do
ModerationLog.insert_log(%{
action: "report_assigned",
actor: admin,
subject: activity,
subject_actor: report.user_actor,
assigned_account: admin.nickname
})
render(conn, "show.json", Report.extract_report_info(report))
else
{:error, :not_found} ->
{:error, :not_found}
{:error, error} ->
json_response(conn, :bad_request, %{error: error})
end
end
def unassign(%{assigns: %{user: admin}} = conn, %{id: id}) do
with {:ok, activity} <- CommonAPI.assign_report_to_account(id, nil),
report <- Activity.get_by_id_with_user_actor(activity.id) do
ModerationLog.insert_log(%{
action: "report_unassigned",
actor: admin,
subject: activity,
subject_actor: report.user_actor
})
render(conn, "show.json", Report.extract_report_info(report))
else
{:error, :not_found} ->
{:error, :not_found}
{:error, error} ->
json_response(conn, :bad_request, %{error: error})
end
end
defp restrict_state(opts, %{resolved: true, unresolved: true}), do: opts
defp restrict_state(opts, %{resolved: true}), do: Map.put(opts, :state, "resolved")
defp restrict_state(opts, _params), do: Map.put(opts, :state, "open")
defp restrict_actor(opts, %{account_id: actor}) do
with %User{ap_id: ap_id} <- User.get_by_id(actor) do
Map.put(opts, :actor_id, ap_id)
else
_ -> Map.put(opts, :actor_id, actor)
end
end
defp restrict_actor(opts, _params), do: opts
defp restrict_target(opts, %{target_account_id: actor}) do
case User.get_by_id(actor) do
%User{ap_id: ap_id} -> Map.put(opts, :report_target_id, ap_id)
_ -> Map.put(opts, :report_target_id, actor)
end
end
defp restrict_target(opts, _params), do: opts
end

View file

@ -1,5 +1,5 @@
# Pleroma: A lightweight social networking server
# Copyright © 2017-2024 Pleroma Authors <https://pleroma.social/>
# Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.MastodonAPI.Admin.AccountView do
@ -24,16 +24,15 @@ defmodule Pleroma.Web.MastodonAPI.Admin.AccountView do
created_at: Utils.to_masto_date(user.inserted_at),
email: user.email,
ip: nil,
role: role(user),
confirmed: user.is_confirmed,
sensitized: nil,
suspended: nil,
silenced: nil,
disabled: !user.is_active,
approved: user.is_approved,
ips: [],
locale: nil,
invite_request: user.registration_reason,
ips: nil,
role: role(user),
confirmed: user.is_confirmed,
approved: user.is_approved,
disabled: !user.is_active,
silenced: nil,
suspended: nil,
account: account
}
end

View file

@ -1,11 +1,12 @@
# Pleroma: A lightweight social networking server
# Copyright © 2017-2024 Pleroma Authors <https://pleroma.social/>
# Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.MastodonAPI.Admin.ReportView do
use Pleroma.Web, :view
alias Pleroma.HTML
alias Pleroma.Rule
alias Pleroma.Web.AdminAPI.Report
alias Pleroma.Web.CommonAPI.Utils
alias Pleroma.Web.MastodonAPI.Admin.AccountView
@ -21,9 +22,12 @@ defmodule Pleroma.Web.MastodonAPI.Admin.ReportView do
report: report,
user: account,
account: target_account,
statuses: statuses
statuses: statuses,
assigned_account: assigned_account
}) do
created_at = Utils.to_masto_date(report.data["published"])
updated_at = Utils.to_masto_date(report.updated_at)
action_taken = report.data["state"] != "open"
content =
unless is_nil(report.data["content"]) do
@ -34,21 +38,34 @@ defmodule Pleroma.Web.MastodonAPI.Admin.ReportView do
%{
id: report.id,
action_taken: report.data["state"] != "open",
action_taken: action_taken,
action_taken_at: if(action_taken, do: updated_at),
category: "other",
comment: content,
forwarded: false,
created_at: created_at,
updated_at: created_at,
updated_at: updated_at,
account: AccountView.render("show.json", %{user: account}),
target_account: AccountView.render("show.json", %{user: target_account}),
assigned_account: nil,
assigned_account: render_account(assigned_account),
action_taken_by_account: nil,
statuses:
StatusView.render("index.json", %{
activities: statuses,
as: :activity
}),
rules: []
rules: rules(report.data["rules"])
}
end
defp render_account(nil), do: nil
defp render_account(account), do: AccountView.render("show.json", %{user: account})
defp rules(nil), do: []
defp rules(rule_ids) do
rule_ids
|> Rule.get()
|> Enum.map(&%{id: to_string(&1.id), text: &1.text})
end
end

View file

@ -5,13 +5,17 @@
defmodule Pleroma.Web.MastodonAPI.NotificationController do
use Pleroma.Web, :controller
import Pleroma.Web.ControllerHelper, only: [add_link_headers: 2]
import Pleroma.Web.ControllerHelper, only: [add_link_headers: 2, add_link_headers: 3]
alias Pleroma.Notification
alias Pleroma.User
alias Pleroma.Web.MastodonAPI.AccountView
alias Pleroma.Web.MastodonAPI.MastodonAPI
alias Pleroma.Web.Plugs.OAuthScopesPlug
@oauth_read_actions [:show, :index]
# Mastodon's docs currently list write:notifications for group accounts, but the endpoint is
# read-only and Mastodon's implementation accepts read:notifications. Prefer least privilege.
@oauth_read_actions [:show, :index, :grouped_index, :show_group, :group_accounts, :unread_count]
plug(Pleroma.Web.ApiSpec.CastAndValidate, replace_params: false)
@ -39,7 +43,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationController do
# GET /api/v1/notifications
def index(%{private: %{open_api_spex: %{params: %{account_id: account_id} = params}}} = conn, _) do
case Pleroma.User.get_cached_by_id(account_id) do
case User.get_cached_by_id(account_id) do
%{ap_id: account_ap_id} ->
params =
params
@ -59,10 +63,108 @@ defmodule Pleroma.Web.MastodonAPI.NotificationController do
do_get_notifications(conn, params)
end
# GET /api/v2/notifications
def grouped_index(
%{private: %{open_api_spex: %{params: %{account_id: account_id} = params}}} = conn,
_
) do
case User.get_cached_by_id(account_id) do
%{ap_id: account_ap_id} ->
params =
params
|> Map.delete(:account_id)
|> Map.put(:account_ap_id, account_ap_id)
do_get_grouped_notifications(conn, params)
_ ->
conn
|> put_status(:not_found)
|> json(%{"error" => "Account is not found"})
end
end
def grouped_index(%{private: %{open_api_spex: %{params: params}}} = conn, _) do
do_get_grouped_notifications(conn, params)
end
# GET /api/v2/notifications/:group_key
def show_group(
%{assigns: %{user: user}, private: %{open_api_spex: %{params: %{group_key: group_key}}}} =
conn,
_
) do
{notifications, notification_group_counts, notification_group_bounds} =
MastodonAPI.get_notification_group_result(user, group_key, %{})
if Enum.empty?(notifications) do
conn
|> put_status(:not_found)
|> json(%{"error" => "Notification group is not found"})
else
grouped_types = if String.starts_with?(group_key, "ungrouped-"), do: [], else: nil
render(conn, "grouped_index.json",
notification_groups: [notifications],
notification_group_counts: notification_group_counts,
notification_group_bounds: notification_group_bounds,
for: user,
grouped_types: grouped_types,
include_page_metadata: false
)
end
end
# GET /api/v2/notifications/:group_key/accounts
def group_accounts(
%{assigns: %{user: user}, private: %{open_api_spex: %{params: %{group_key: group_key}}}} =
conn,
_
) do
# Mastodon paginates this endpoint in code, but the public docs say it returns accounts of all
# notifications in the group and do not document cursor params here. Follow the documented API.
users = MastodonAPI.get_notification_group_accounts(user, group_key)
json(conn, AccountView.render("index.json", %{users: users, for: user}))
end
# GET /api/v2/notifications/unread_count
def unread_count(
%{private: %{open_api_spex: %{params: %{account_id: account_id} = params}}} = conn,
_
) do
case User.get_cached_by_id(account_id) do
%{ap_id: account_ap_id} ->
params =
params
|> Map.delete(:account_id)
|> Map.put(:account_ap_id, account_ap_id)
do_get_unread_group_count(conn, params)
_ ->
conn
|> put_status(:not_found)
|> json(%{"error" => "Account is not found"})
end
end
def unread_count(%{private: %{open_api_spex: %{params: params}}} = conn, _) do
do_get_unread_group_count(conn, params)
end
# POST /api/v2/notifications/:group_key/dismiss
def dismiss_group(
%{assigns: %{user: user}, private: %{open_api_spex: %{params: %{group_key: group_key}}}} =
conn,
_
) do
MastodonAPI.dismiss_notification_group(user, group_key)
json(conn, %{})
end
defp do_get_notifications(%{assigns: %{user: user}} = conn, params) do
params =
Map.new(params, fn {k, v} -> {to_string(k), v} end)
|> Map.put_new("types", Map.get(params, :include_types, @default_notification_types))
params = normalize_notification_params(params)
notifications = MastodonAPI.get_notifications(user, params)
@ -74,6 +176,35 @@ defmodule Pleroma.Web.MastodonAPI.NotificationController do
)
end
defp do_get_grouped_notifications(%{assigns: %{user: user}} = conn, params) do
params = normalize_notification_params(params)
{notification_groups, page_notifications, notification_group_counts,
notification_group_bounds} =
MastodonAPI.get_grouped_notification_page(user, params)
conn
|> add_link_headers(page_notifications, %{drop_id_params: true})
|> render("grouped_index.json",
notification_groups: notification_groups,
notification_group_counts: notification_group_counts,
notification_group_bounds: notification_group_bounds,
for: user,
grouped_types: params["grouped_types"]
)
end
defp do_get_unread_group_count(%{assigns: %{user: user}} = conn, params) do
params = normalize_notification_params(params)
json(conn, %{count: MastodonAPI.unread_notification_group_count(user, params)})
end
defp normalize_notification_params(params) do
params
|> Map.new(fn {k, v} -> {to_string(k), v} end)
|> Map.put_new("types", Map.get(params, :include_types, @default_notification_types))
end
# GET /api/v1/notifications/:id
def show(%{assigns: %{user: user}, private: %{open_api_spex: %{params: %{id: id}}}} = conn, _) do
with {:ok, notification} <- Notification.get(user, id) do

View file

@ -716,7 +716,10 @@ defmodule Pleroma.Web.MastodonAPI.StatusController do
end
end
defp put_application(params, %{assigns: %{token: %Token{user: %User{} = user} = token}} = _conn) do
defp put_application(
params,
%{assigns: %{token: %Token{} = token, user: %User{} = user}} = _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})

View file

@ -6,12 +6,16 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPI do
import Ecto.Query
import Ecto.Changeset
alias Pleroma.Marker
alias Pleroma.Notification
alias Pleroma.Pagination
alias Pleroma.Repo
alias Pleroma.ScheduledActivity
alias Pleroma.User
alias Pleroma.Web.CommonAPI
@notification_group_sample_limit 8
@spec follow(User.t(), User.t(), map) :: {:ok, User.t()} | {:error, String.t()}
def follow(follower, followed, params \\ %{}) do
result =
@ -61,29 +65,365 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPI do
end
def get_notifications(user, params \\ %{}) do
options =
cast_params(params) |> Map.update(:include_types, [], fn include_types -> include_types end)
user
|> notifications_query(params)
|> Pagination.fetch_paginated(params)
end
options =
if ("pleroma:report" not in options.include_types and
User.privileged?(user, :reports_manage_reports)) or
User.privileged?(user, :reports_manage_reports) do
options
else
options
|> Map.update(:exclude_types, ["pleroma:report"], fn current_exclude_types ->
current_exclude_types ++ ["pleroma:report"]
end)
end
def get_grouped_notification_page(user, params \\ %{}) do
grouped_types =
params
|> Map.get("grouped_types")
|> Notification.normalize_grouped_types()
query = notifications_query(user, params)
{order, cursor_filters} = group_pagination(params)
group_rows =
query
|> notification_group_rows(grouped_types, grouped_limit(params), order, cursor_filters)
group_rows = if order == :asc, do: Enum.reverse(group_rows), else: group_rows
page_notifications = representative_notifications(query, group_rows)
notification_groups =
Enum.map(group_rows, &notification_group_sample(user, params, &1.group_key))
{
notification_groups,
page_notifications,
notification_group_counts(group_rows),
notification_group_bounds(group_rows)
}
end
def get_notification_group_result(user, group_key, params \\ %{}) do
notifications = notification_group_sample(user, params, group_key)
metadata = notification_group_metadata(user, group_key, params)
if Enum.empty?(notifications) or is_nil(metadata) do
{[], %{}, %{}}
else
{
notifications,
%{group_key => metadata.notifications_count},
%{group_key => Map.drop(metadata, [:notifications_count])}
}
end
end
def get_notification_group(user, group_key, params \\ %{})
def get_notification_group(user, "ungrouped-" <> notification_id, _params) do
case Notification.get(user, notification_id) do
{:ok, notification} -> [notification]
_ -> []
end
end
def get_notification_group(user, group_key, params) do
notification_group_sample(user, params, group_key)
end
def get_notification_group_accounts(user, "ungrouped-" <> notification_id) do
with {:ok, notification} <- Notification.get(user, notification_id),
%User{} = actor <- User.get_cached_by_ap_id(notification.activity.data["actor"]) do
[actor]
else
_ -> []
end
end
def get_notification_group_accounts(user, group_key) do
user
|> notification_group_query(group_key, %{})
|> exclude(:preload)
|> distinct(true)
|> select([user_actor: user_actor], user_actor)
|> Repo.all()
end
def dismiss_notification_group(user, "ungrouped-" <> notification_id) do
Notification.destroy_multiple(user, [notification_id])
end
def dismiss_notification_group(%User{id: user_id}, group_key) do
Notification
|> where([n], n.user_id == ^user_id and n.group_key == ^group_key)
|> Repo.delete_all()
end
defp group_pagination(params) do
cond do
min_id = Map.get(params, "min_id") ->
cursor_filters = [{:gt, min_id}]
cursor_filters =
case Map.get(params, "max_id") do
nil -> cursor_filters
max_id -> [{:lt, max_id} | cursor_filters]
end
{:asc, cursor_filters}
since_id = Map.get(params, "since_id") ->
{:desc, [{:gt, since_id}]}
max_id = Map.get(params, "max_id") ->
{:desc, [{:lt, max_id}]}
true ->
{:desc, []}
end
end
defp grouped_limit(params) do
params
|> Map.get("limit", 40)
|> parse_limit(40)
|> min(80)
end
def unread_notification_group_count(user, params \\ %{}) do
grouped_types =
params
|> Map.get("grouped_types")
|> Notification.normalize_grouped_types()
limit = unread_count_limit(params)
user
|> notifications_query(params)
# The grouped API docs define unread by the notifications marker, not by Pleroma's per-row
# seen flag used by the v1 unread count. Keep this marker-based for Mastodon clients.
|> restrict_after_marker(notification_marker_last_read_id(user))
|> notification_group_rows(grouped_types, limit, :desc, [])
|> length()
end
defp notification_group_rows(query, grouped_types, group_limit, :desc, cursor_filters) do
query
|> notification_group_keyed_query(grouped_types)
|> group_by([n], n.group_key)
|> apply_group_cursor_filters(cursor_filters)
|> select([n], %{
group_key: n.group_key,
representative_id: max(n.id),
notifications_count: count(n.id),
page_min_id: min(n.id),
page_max_id: max(n.id),
latest_page_notification_at: max(n.inserted_at)
})
|> order_by([n], desc: max(n.id))
|> limit(^group_limit)
|> Repo.all()
end
defp notification_group_rows(query, grouped_types, group_limit, :asc, cursor_filters) do
query
|> notification_group_keyed_query(grouped_types)
|> group_by([n], n.group_key)
|> apply_group_cursor_filters(cursor_filters)
|> select([n], %{
group_key: n.group_key,
representative_id: max(n.id),
notifications_count: count(n.id),
page_min_id: min(n.id),
page_max_id: max(n.id),
latest_page_notification_at: max(n.inserted_at)
})
|> order_by([n], asc: max(n.id))
|> limit(^group_limit)
|> Repo.all()
end
defp apply_group_cursor_filters(query, []), do: query
defp apply_group_cursor_filters(query, [{:gt, id} | rest]) do
query
|> having([n], max(n.id) > ^id)
|> apply_group_cursor_filters(rest)
end
defp apply_group_cursor_filters(query, [{:lt, id} | rest]) do
query
|> having([n], max(n.id) < ^id)
|> apply_group_cursor_filters(rest)
end
defp notification_group_keyed_query(query, grouped_types) do
query
|> exclude(:preload)
|> select([n], %{
id: n.id,
inserted_at: n.inserted_at,
group_key:
fragment(
"CASE WHEN ? IS NOT NULL AND ?::text = ANY(?) THEN ? ELSE 'ungrouped-' || ?::text END",
n.group_key,
n.type,
type(^grouped_types, {:array, :string}),
n.group_key,
n.id
)
})
|> subquery()
end
defp representative_notifications(_query, []), do: []
defp representative_notifications(query, group_rows) do
representative_ids = Enum.map(group_rows, & &1.representative_id)
notifications_by_id =
query
|> where([n], n.id in ^representative_ids)
|> Repo.all()
|> Map.new(&{to_string(&1.id), &1})
group_rows
|> Enum.map(&Map.get(notifications_by_id, to_string(&1.representative_id)))
|> Enum.filter(& &1)
end
defp notification_group_counts(group_rows) do
Map.new(group_rows, &{&1.group_key, &1.notifications_count})
end
defp notification_group_bounds(group_rows) do
Map.new(group_rows, fn row ->
{row.group_key,
%{
page_min_id: row.page_min_id,
page_max_id: row.page_max_id,
latest_page_notification_at: row.latest_page_notification_at
}}
end)
end
defp notification_group_sample(user, _params, "ungrouped-" <> notification_id) do
case Notification.get(user, notification_id) do
{:ok, notification} -> [notification]
_ -> []
end
end
defp notification_group_sample(user, params, group_key) do
user
|> notification_group_query(group_key, params)
|> order_by([n], desc: n.id)
|> limit(^@notification_group_sample_limit)
|> Repo.all()
end
defp notification_group_metadata(user, "ungrouped-" <> notification_id, _params) do
case Notification.get(user, notification_id) do
{:ok, notification} ->
%{
notifications_count: 1,
page_min_id: notification.id,
page_max_id: notification.id,
latest_page_notification_at: notification.inserted_at
}
_ ->
nil
end
end
defp notification_group_metadata(user, group_key, params) do
user
|> notification_group_query(group_key, params)
|> exclude(:preload)
|> select([n], %{
notifications_count: count(n.id),
page_min_id: min(n.id),
page_max_id: max(n.id),
latest_page_notification_at: max(n.inserted_at)
})
|> Repo.one()
|> case do
%{notifications_count: 0} -> nil
metadata -> metadata
end
end
defp notification_group_query(user, group_key, params) do
user
|> notifications_query(params)
|> where([n], n.group_key == ^group_key)
end
defp notification_marker_last_read_id(user) do
Marker
|> where([m], m.user_id == ^user.id and m.timeline == "notifications")
|> select([m], m.last_read_id)
|> Repo.one()
end
defp restrict_after_marker(query, last_read_id)
when is_binary(last_read_id) and last_read_id != "" do
where(query, [n], n.id > ^last_read_id)
end
defp restrict_after_marker(query, _last_read_id), do: query
defp notifications_query(user, params) do
options = notification_options(user, params)
user
|> Notification.for_user_query(options)
|> restrict(:types, options)
|> restrict(:exclude_types, options)
|> restrict(:account_ap_id, options)
|> Pagination.fetch_paginated(params)
end
defp notification_options(user, params) do
options =
params
|> cast_params()
|> Map.update(:include_types, [], fn include_types -> include_types end)
if "pleroma:chat_mention" in options.include_types and not Pleroma.Chat.enabled?() do
options
|> Map.update(:include_types, [], fn include_types ->
List.delete(include_types, "pleroma:chat_mention")
end)
else
options
end
if ("pleroma:report" not in options.include_types and
User.privileged?(user, :reports_manage_reports)) or
User.privileged?(user, :reports_manage_reports) do
options
else
options
|> Map.update(:exclude_types, ["pleroma:report"], fn current_exclude_types ->
current_exclude_types ++ ["pleroma:report"]
end)
end
end
defp unread_count_limit(params) do
params
|> Map.get("limit", 100)
|> parse_limit(100)
|> min(1000)
end
defp parse_limit(limit, _default) when is_integer(limit) and limit > 0, do: limit
defp parse_limit(limit, default) when is_binary(limit) do
case Integer.parse(limit) do
{limit, _} when limit > 0 -> limit
_ -> default
end
end
defp parse_limit(_, default), do: default
def get_scheduled_activities(user, params \\ %{}) do
user
|> ScheduledActivity.for_user_query()
@ -95,6 +435,8 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPI do
exclude_types: {:array, :string},
types: {:array, :string},
exclude_visibilities: {:array, :string},
grouped_types: {:array, :string},
limit: :integer,
reblogs: :boolean,
with_muted: :boolean,
account_ap_id: :string,

View file

@ -287,6 +287,8 @@ defmodule Pleroma.Web.MastodonAPI.AccountView do
user.last_status_at &&
user.last_status_at |> NaiveDateTime.to_date() |> Date.to_iso8601()
accepts_chat_messages = Pleroma.Chat.enabled?() and user.accepts_chat_messages
%{
id: to_string(user.id),
username: username_from_nickname(user.nickname),
@ -336,7 +338,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountView do
relationship: relationship,
skip_thread_containment: user.skip_thread_containment,
background_image: image_url(user.background) |> MediaProxy.url(),
accepts_chat_messages: user.accepts_chat_messages,
accepts_chat_messages: accepts_chat_messages,
favicon: favicon,
avatar_description: avatar_description,
header_description: header_description
@ -391,6 +393,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountView do
|> Kernel.put_in([:source, :pleroma, :show_role], user.show_role)
|> Kernel.put_in([:source, :pleroma, :no_rich_text], user.no_rich_text)
|> Kernel.put_in([:source, :pleroma, :show_birthday], user.show_birthday)
|> Kernel.put_in([:source, :pleroma, :accepts_chat_messages], user.accepts_chat_messages)
end
defp maybe_put_settings(data, _, _, _), do: data

View file

@ -17,6 +17,8 @@ defmodule Pleroma.Web.MastodonAPI.InstanceView do
reject: "suspend"
}
def mastodon_api_level, do: @mastodon_api_level
def render("show.json", _) do
instance = Config.get(:instance)
@ -166,6 +168,7 @@ defmodule Pleroma.Web.MastodonAPI.InstanceView do
[
"pleroma_api",
"mastodon_api",
"mastodon_api_grouped_notifications",
"mastodon_api_streaming",
"polls",
"v2_suggestions",
@ -199,8 +202,12 @@ defmodule Pleroma.Web.MastodonAPI.InstanceView do
end,
"pleroma_emoji_reactions",
"pleroma_custom_emoji_reactions",
"pleroma_chat_messages",
"pleroma:pin_chats",
if Pleroma.Chat.enabled?() do
"pleroma_chat_messages"
end,
if Pleroma.Chat.enabled?() do
"pleroma:pin_chats"
end,
if Config.get([:instance, :show_reactions]) do
"exposable_reactions"
end,

View file

@ -4,6 +4,8 @@
defmodule Pleroma.Web.MastodonAPI.ListView do
use Pleroma.Web, :view
alias Pleroma.Emoji
alias Pleroma.Web.MastodonAPI.ListView
def render("index.json", %{lists: lists} = opts) do
@ -11,10 +13,29 @@ defmodule Pleroma.Web.MastodonAPI.ListView do
end
def render("show.json", %{list: list}) do
{emoji, emoji_url} = get_emoji(list.emoji)
%{
id: to_string(list.id),
title: list.title,
exclusive: list.exclusive
exclusive: list.exclusive,
pleroma: %{
emoji: emoji,
emoji_url: emoji_url
}
}
end
defp get_emoji(nil), do: {nil, nil}
defp get_emoji(emoji) do
if Emoji.unicode?(emoji) do
{emoji, nil}
else
case Emoji.get(emoji) do
nil -> {nil, nil}
emoji_data -> {emoji, Emoji.local_url(emoji_data.file)}
end
end
end
end

View file

@ -72,6 +72,58 @@ defmodule Pleroma.Web.MastodonAPI.NotificationView do
safe_render_many(notifications, NotificationView, "show.json", opts)
end
def render("grouped_index.json", %{notifications: notifications} = opts) do
grouped_types = Notification.normalize_grouped_types(opts[:grouped_types])
opts
|> Map.delete(:notifications)
|> Map.put(
:notification_groups,
Notification.group_notifications(notifications, grouped_types)
)
|> then(&render("grouped_index.json", &1))
end
def render(
"grouped_index.json",
%{notification_groups: notification_groups, for: reading_user} = opts
) do
grouped_types = Notification.normalize_grouped_types(opts[:grouped_types])
notification_group_counts = Map.get(opts, :notification_group_counts, %{})
notification_group_bounds = Map.get(opts, :notification_group_bounds, %{})
include_page_metadata = Map.get(opts, :include_page_metadata, true)
statuses =
notification_groups
|> Enum.map(&List.first/1)
|> Enum.map(&render("show.json", %{notification: &1, for: reading_user}))
|> Enum.map(& &1[:status])
|> Enum.filter(& &1)
|> Enum.uniq_by(& &1[:id])
actors =
notification_groups
|> List.flatten()
|> notification_actors()
%{
accounts: AccountView.render("index.json", %{users: actors, for: reading_user}),
statuses: statuses,
notification_groups:
Enum.map(
notification_groups,
&render_group(
&1,
reading_user,
grouped_types,
notification_group_counts,
notification_group_bounds,
include_page_metadata
)
)
}
end
def render(
"show.json",
%{
@ -95,7 +147,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationView do
response = %{
id: to_string(notification.id),
group_key: "ungrouped-" <> to_string(notification.id),
group_key: Notification.group_key(notification),
type: notification.type,
created_at: CommonAPI.Utils.to_masto_date(notification.inserted_at),
account: account,
@ -137,6 +189,104 @@ defmodule Pleroma.Web.MastodonAPI.NotificationView do
Map.put(response, :report, report_render)
end
defp render_group(
[%Notification{} = notification | _] = notifications,
_reading_user,
grouped_types,
notification_group_counts,
notification_group_bounds,
include_page_metadata
) do
latest_notification = List.first(notifications)
oldest_notification = List.last(notifications)
status_activity = status_activity_for_group(notifications, grouped_types)
group_key = Notification.group_key(notification, grouped_types)
bounds = Map.get(notification_group_bounds, group_key, %{})
response = %{
group_key: group_key,
notifications_count: Map.get(notification_group_counts, group_key, length(notifications)),
type: notification.type,
most_recent_notification_id:
bounds
|> Map.get(:page_max_id, latest_notification.id)
|> to_string(),
sample_account_ids:
notifications
|> notification_actors()
|> Enum.map(&to_string(&1.id))
}
response =
if include_page_metadata do
Map.merge(response, %{
page_min_id:
bounds
|> Map.get(:page_min_id, oldest_notification.id)
|> to_string(),
page_max_id:
bounds
|> Map.get(:page_max_id, latest_notification.id)
|> to_string(),
latest_page_notification_at:
bounds
|> Map.get(:latest_page_notification_at, latest_notification.inserted_at)
|> CommonAPI.Utils.to_masto_date()
})
else
response
end
if status_activity do
Map.put(response, :status_id, to_string(status_activity.id))
else
response
end
end
defp status_activity_for_group([%Notification{} = notification | _], grouped_types) do
status_activity_for(notification, grouped_types)
end
defp status_activity_for(%Notification{type: type, activity: activity}, _grouped_types)
when type in ["mention", "status", "poll"] do
activity
end
defp status_activity_for(%Notification{type: type} = notification, grouped_types)
when type in ["favourite", "reblog"] do
group_key = Notification.group_key(notification, grouped_types)
case String.split(group_key, "-", parts: 3) do
[^type, activity_id, _bucket] ->
case Activity.create_by_id_with_object(activity_id) do
%Activity{} = activity -> activity
_ -> parent_status_activity(notification.activity)
end
_ ->
parent_status_activity(notification.activity)
end
end
defp status_activity_for(%Notification{type: type, activity: activity}, _grouped_types)
when type in ["update", "pleroma:emoji_reaction"] do
parent_status_activity(activity)
end
defp status_activity_for(_, _grouped_types), do: nil
defp parent_status_activity(activity) do
Activity.get_create_by_object_ap_id(object_id_for(activity))
end
defp notification_actors(notifications) do
notifications
|> Enum.map(&User.get_cached_by_ap_id(&1.activity.data["actor"]))
|> Enum.filter(& &1)
|> Enum.uniq_by(& &1.id)
end
defp put_emoji(response, activity) do
response
|> Map.put(:emoji, activity.data["content"])

View file

@ -587,14 +587,25 @@ defmodule Pleroma.Web.MastodonAPI.StatusView do
video_url = proxied_url(rich_media["video"], page_url_data)
%{
type: "link",
provider_name: page_url_data.host,
provider_url: page_url_data.scheme <> "://" <> page_url_data.host,
type: card_type(rich_media["type"]),
provider_name: rich_media["provider_name"] || page_url_data.host,
provider_url:
rich_media["provider_url"] || page_url_data.scheme <> "://" <> page_url_data.host,
url: page_url,
image: image_url,
image_description: rich_media["image:alt"] || "",
title: rich_media["title"] || "",
description: rich_media["description"] || "",
language: nil,
authors: [],
author_name: rich_media["author_name"] || "",
author_url: rich_media["author_url"] || "",
html: rich_media["html"] || "",
width: card_dimension(rich_media["width"]),
height: card_dimension(rich_media["height"]),
embed_url: rich_media["embed_url"] || "",
blurhash: nil,
published_at: nil,
pleroma: %{
opengraph:
rich_media
@ -620,6 +631,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusView do
String.contains?(media_type, "image") -> "image"
String.contains?(media_type, "video") -> "video"
String.contains?(media_type, "audio") -> "audio"
attachment["type"] == "Image" -> "image"
true -> "unknown"
end
@ -698,6 +710,20 @@ defmodule Pleroma.Web.MastodonAPI.StatusView do
%{content: content, detected_source_language: detected_source_language, provider: provider}
end
defp card_type(type) when type in ["link", "photo", "video", "rich"], do: type
defp card_type(_), do: "link"
defp card_dimension(value) when is_integer(value) and value >= 0, do: value
defp card_dimension(value) when is_binary(value) do
case Integer.parse(value) do
{dimension, ""} when dimension >= 0 -> dimension
_ -> 0
end
end
defp card_dimension(_), do: 0
def get_reply_to(activity, %{replied_to_activities: replied_to_activities}) do
object = Object.normalize(activity, fetch: false)

View file

@ -208,6 +208,7 @@ defmodule Pleroma.Web.MediaProxy.MediaProxyController do
defp media_proxy_opts do
Config.get([:media_proxy, :proxy_opts], [])
|> Keyword.put_new(:sniff_content_type, true)
end
defp sandbox(conn, _params) do

View file

@ -41,6 +41,7 @@ defmodule Pleroma.Web.PleromaAPI.ChatController do
)
plug(Pleroma.Web.ApiSpec.CastAndValidate, replace_params: false)
plug(:ensure_chats_enabled)
defdelegate open_api_operation(action), to: Pleroma.Web.ApiSpec.ChatOperation
@ -244,4 +245,16 @@ defmodule Pleroma.Web.PleromaAPI.ChatController do
_ -> nil
end
end
defp ensure_chats_enabled(conn, _opts) do
if Chat.enabled?() do
conn
else
conn
|> put_status(:not_found)
|> put_view(Pleroma.Web.ErrorView)
|> render("404.json")
|> halt()
end
end
end

View file

@ -4,6 +4,7 @@
defmodule Pleroma.Web.Plugs.EnsureHostMatchesPlug do
@moduledoc "Ensures Host header matches instance"
@behaviour Plug
alias Pleroma.Web.Endpoint

View file

@ -4,7 +4,7 @@
defmodule Pleroma.Web.Plugs.InstanceStatic do
require Pleroma.Constants
import Plug.Conn, only: [put_resp_header: 3, put_status: 2, send_resp: 3, halt: 1]
import Plug.Conn, only: [put_resp_header: 3]
@moduledoc """
This is a shim to call `Plug.Static` but with runtime `from` configuration.
@ -51,37 +51,10 @@ defmodule Pleroma.Web.Plugs.InstanceStatic do
|> Map.put(:from, from)
|> Map.put(:content_types, false)
conn =
conn
|> set_content_type(conn.request_path)
|> Plug.Static.call(opts)
conn = set_content_type(conn, conn.request_path)
if conn.halted do
conn
else
path = String.trim_leading(conn.request_path, "/")
if not File.exists?(file_path(path)) do
conn
|> put_status(:not_found)
|> send_404()
|> halt()
else
conn
end
end
end
defp send_404(conn) do
if String.ends_with?(String.downcase(conn.request_path), ".json") do
conn
|> put_resp_header("content-type", "application/json")
|> send_resp(404, Jason.encode!(%{error: "not found"}))
else
conn
|> put_resp_header("content-type", "text/plain")
|> send_resp(404, "Not found")
end
# Call Plug.Static with our sanitized content-type
Plug.Static.call(conn, opts)
end
defp set_content_type(conn, "/emoji/" <> filepath) do

View file

@ -52,7 +52,7 @@ defmodule Pleroma.Web.Plugs.OAuthPlug do
where: t.token == ^token
)
with %Token{user_id: user_id} = token_record <- Repo.one(token_query) |> Repo.preload(:user),
with %Token{user_id: user_id} = token_record <- Repo.one(token_query),
false <- is_nil(user_id),
%User{} = user <- User.get_cached_by_id(user_id) do
{:ok, user, token_record}

View file

@ -0,0 +1,38 @@
# Pleroma: A lightweight social networking server
# Copyright © 2017-2026 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.Plugs.StaticNotFoundPlug do
@moduledoc """
A small plug that enforces returning 404 on static files when they don't exist.
"""
@behaviour Plug
require Pleroma.Constants
import Plug.Conn, only: [put_resp_header: 3, send_resp: 3, halt: 1]
def init(opts), do: opts
for only <- Pleroma.Constants.static_only_files() do
def call(%{request_path: "/" <> unquote(only) <> _} = conn, _opts) do
send_404(conn)
end
end
def call(conn, _) do
conn
end
defp send_404(conn) do
if String.ends_with?(String.downcase(conn.request_path), ".json") do
conn
|> put_resp_header("content-type", "application/json")
|> send_resp(404, Jason.encode!(%{error: "not found"}))
else
conn
|> put_resp_header("content-type", "text/plain")
|> send_resp(404, "Not found")
end
|> halt()
end
end

View file

@ -4,6 +4,8 @@
defmodule Pleroma.Web.RichMedia.Helpers do
alias Pleroma.Config
alias Pleroma.Gun.ConnectionPool
alias Pleroma.ReverseProxy.Client.Tesla, as: TeslaClient
require Logger
@ -19,12 +21,30 @@ defmodule Pleroma.Web.RichMedia.Helpers do
end
defp stream(url) do
with {_, {:ok, %Tesla.Env{status: 200, body: stream_body, headers: headers}}} <-
{:get, Pleroma.HTTP.get(url, req_headers(), http_options())},
{_, :ok} <- {:content_type, check_content_type(headers)},
{_, :ok} <- {:content_length, check_content_length(headers)},
{:read_stream, {:ok, body}} <- {:read_stream, read_stream(stream_body)} do
{:ok, body}
case Pleroma.HTTP.get(url, req_headers(), http_options()) do
{:ok, %Tesla.Env{status: 200, body: stream_body, headers: headers}} ->
result =
try do
with {_, :ok} <- {:content_type, check_content_type(headers)},
{_, :ok} <- {:content_length, check_content_length(headers)},
{:read_stream, {:ok, body}} <- {:read_stream, read_stream(stream_body)} do
{:ok, body}
end
rescue
exception ->
cleanup_stream(stream_body, :error)
reraise exception, __STACKTRACE__
end
cleanup_stream(stream_body, result)
result
{:ok, %Tesla.Env{body: stream_body}} = response ->
cleanup_stream(stream_body, :rejected)
{:get, response}
response ->
{:get, response}
end
end
@ -95,6 +115,10 @@ defmodule Pleroma.Web.RichMedia.Helpers do
end
end
defp read_stream(%{pid: pid, stream: stream, opts: opts}) do
read_chunks(pid, stream, opts, "", 0, Keyword.get(http_options(), :max_body))
end
defp read_stream(stream) do
max_body = Keyword.get(http_options(), :max_body)
@ -117,6 +141,33 @@ defmodule Pleroma.Web.RichMedia.Helpers do
end
end
defp read_chunks(pid, stream, opts, acc, total_bytes, max_body) do
case Tesla.Adapter.Gun.read_chunk(pid, stream, opts) do
{fin, chunk} when fin in [:fin, :nofin] ->
total_bytes = total_bytes + byte_size(chunk)
cond do
total_bytes > max_body ->
:error
fin == :fin ->
{:ok, acc <> chunk}
true ->
read_chunks(pid, stream, opts, acc <> chunk, total_bytes, max_body)
end
{:error, _reason} ->
:error
end
end
defp cleanup_stream(%{pid: pid, stream: stream}, {:ok, _body}),
do: ConnectionPool.release_stream(pid, stream)
defp cleanup_stream(%{pid: _pid} = client, _result), do: TeslaClient.close(client)
defp cleanup_stream(_stream, _result), do: :ok
defp http_options do
[
pool: :rich_media,

View file

@ -137,6 +137,12 @@ defmodule Pleroma.Web.Router do
plug(Pleroma.Web.Plugs.EnsurePrivilegedPlug, :users_manage_activation_state)
end
pipeline :require_privileged_role_account_actions do
plug(:admin_api)
plug(Pleroma.Web.Plugs.EnsurePrivilegedPlug, :users_manage_activation_state)
plug(Pleroma.Web.Plugs.EnsurePrivilegedPlug, :reports_manage_reports)
end
pipeline :require_privileged_role_users_manage_invites do
plug(:admin_api)
plug(Pleroma.Web.Plugs.EnsurePrivilegedPlug, :users_manage_invites)
@ -433,6 +439,60 @@ defmodule Pleroma.Web.Router do
delete("/chats/:id/messages/:message_id", ChatController, :delete_message)
end
# Mastodon AdminAPI: admins and mods (staff) can perform these actions (if privileged by role)
scope "/api/v1/admin", Pleroma.Web.MastodonAPI.Admin do
pipe_through([:require_privileged_role_users_read])
get("/accounts", AccountController, :index)
get("/accounts/:id", AccountController, :show)
end
# Mastodon AdminAPI: admins and mods (staff) can perform these actions (if privileged by role)
scope "/api/v1/admin", Pleroma.Web.MastodonAPI.Admin do
pipe_through(:require_privileged_role_users_delete)
delete("/accounts/:id", AccountController, :delete)
end
# Mastodon AdminAPI: admins and mods (staff) can perform these actions (if privileged by role)
scope "/api/v1/admin", Pleroma.Web.MastodonAPI.Admin do
pipe_through([:require_privileged_role_users_manage_activation_state])
post("/accounts/:id/enable", AccountController, :enable)
end
scope "/api/v1/admin", Pleroma.Web.MastodonAPI.Admin do
pipe_through([:require_privileged_role_account_actions])
post("/accounts/:id/action", AccountController, :account_action)
end
# Mastodon AdminAPI: admins and mods (staff) can perform these actions (if privileged by role)
scope "/api/v1/admin", Pleroma.Web.MastodonAPI.Admin do
pipe_through([:require_privileged_role_users_manage_invites])
post("/accounts/:id/approve", AccountController, :approve)
post("/accounts/:id/reject", AccountController, :reject)
end
# Mastodon AdminAPI: admins and mods (staff) can perform these actions (if privileged by role)
scope "/api/v1/admin", Pleroma.Web.MastodonAPI.Admin do
pipe_through([:require_privileged_role_reports_manage_reports])
get("/reports", ReportController, :index)
get("/reports/:id", ReportController, :show)
post("/reports/:id/resolve", ReportController, :resolve)
post("/reports/:id/reopen", ReportController, :reopen)
post("/reports/:id/assign_to_self", ReportController, :assign_to_self)
post("/reports/:id/unassign", ReportController, :unassign)
end
# Mastodon AdminAPI: admins and mods (staff) can perform these actions (if privileged by role)
scope "/api/v2/admin", Pleroma.Web.MastodonAPI.Admin do
pipe_through([:require_privileged_role_users_read])
get("/accounts", AccountController, :index2)
end
# AdminAPI: admins and mods (staff) can perform these actions (if privileged by role)
scope "/api/v1/pleroma/admin", Pleroma.Web.AdminAPI do
pipe_through(:require_privileged_role_emoji_manage_emoji)
@ -853,6 +913,16 @@ defmodule Pleroma.Web.Router do
get("/directory", DirectoryController, :index)
end
scope "/api/v2", Pleroma.Web.MastodonAPI do
pipe_through(:authenticated_api)
get("/notifications", NotificationController, :grouped_index)
get("/notifications/unread_count", NotificationController, :unread_count)
get("/notifications/:group_key/accounts", NotificationController, :group_accounts)
get("/notifications/:group_key", NotificationController, :show_group)
post("/notifications/:group_key/dismiss", NotificationController, :dismiss_group)
end
scope "/api/v2", Pleroma.Web.MastodonAPI do
pipe_through(:api)

View file

@ -195,6 +195,9 @@ defmodule Pleroma.Web.Streamer do
recipients = MapSet.new(item.recipients)
domain_blocks = Pleroma.Web.ActivityPub.MRF.subdomains_regex(user.domain_blocks)
following_ap_ids =
if user.domain_blocks == [], do: [], else: User.get_cached_user_friends_ap_ids(user)
with parent <- Object.normalize(item, fetch: false) || item,
true <- Enum.all?([blocked_ap_ids, muted_ap_ids], &(item.actor not in &1)),
true <- item.data["type"] != "Announce" || item.actor not in reblog_muted_ap_ids,
@ -205,8 +208,12 @@ defmodule Pleroma.Web.Streamer do
true <- MapSet.disjoint?(recipients, recipient_blocks),
%{host: item_host} <- URI.parse(item.actor),
%{host: parent_host} <- URI.parse(parent.data["actor"]),
false <- Pleroma.Web.ActivityPub.MRF.subdomain_match?(domain_blocks, item_host),
false <- Pleroma.Web.ActivityPub.MRF.subdomain_match?(domain_blocks, parent_host),
false <-
item.actor not in following_ap_ids and
Pleroma.Web.ActivityPub.MRF.subdomain_match?(domain_blocks, item_host),
false <-
parent.data["actor"] not in following_ap_ids and
Pleroma.Web.ActivityPub.MRF.subdomain_match?(domain_blocks, parent_host),
true <- thread_containment(item, user),
false <- CommonAPI.thread_muted?(parent, user) do
false
@ -289,15 +296,17 @@ defmodule Pleroma.Web.Streamer do
defp do_stream(topic, {user, %MessageReference{} = cm_ref})
when topic in ["user", "user:pleroma_chat"] do
topic = "#{topic}:#{user.id}"
if Pleroma.Chat.enabled?() do
topic = "#{topic}:#{user.id}"
text = StreamerView.render("chat_update.json", %{chat_message_reference: cm_ref}, topic)
text = StreamerView.render("chat_update.json", %{chat_message_reference: cm_ref}, topic)
Registry.dispatch(@registry, topic, fn list ->
Enum.each(list, fn {pid, _auth} ->
send(pid, {:text, text})
Registry.dispatch(@registry, topic, fn list ->
Enum.each(list, fn {pid, _auth} ->
send(pid, {:text, text})
end)
end)
end)
end
end
defp do_stream("user", %Activity{} = item) do

View file

@ -1,9 +1,9 @@
<entry>
<activity:object-type>http://activitystrea.ms/schema/1.0/note</activity:object-type>
<activity:verb>http://activitystrea.ms/schema/1.0/post</activity:verb>
<id><%= @data["id"] %></id>
<id><%= escape(@data["id"] || "") %></id>
<title><%= activity_title(@data, Keyword.get(@feed_config, :post_title, %{})) %></title>
<content type="html"><%= activity_description(@data) %></content>
<content type="html"><%= escape(atom_content_encoded(@data)) %></content>
<published><%= to_rfc3339(@data["published"]) %></published>
<updated><%= to_rfc3339(@data["published"]) %></updated>
<ostatus:conversation ref="<%= activity_context(@activity) %>">
@ -15,35 +15,26 @@
<summary><%= escape(@data["summary"]) %></summary>
<% end %>
<%= if @activity.local do %>
<link type="application/atom+xml" href='<%= @data["id"] %>' rel="self"/>
<link type="text/html" href='<%= @data["id"] %>' rel="alternate"/>
<% else %>
<link type="text/html" href='<%= @data["external_url"] %>' rel="alternate"/>
<% end %>
<link type="text/html" href='<%= escape(activity_link(@activity, @data) || "") %>' rel="alternate"/>
<%= for tag <- Pleroma.Object.hashtags(@object) do %>
<category term="<%= tag %>"></category>
<% end %>
<%= for attachment <- @data["attachment"] || [] do %>
<link rel="enclosure" href="<%= attachment_href(attachment) %>" type="<%= attachment_type(attachment) %>"/>
<%= unless sensitive?(@data) do %>
<%= for attachment <- @data["attachment"] || [] do %>
<%= if size = attachment_size_positive(attachment) do %>
<link rel="enclosure" href="<%= escape(attachment_href(attachment) || "") %>" type="<%= escape(attachment_type(attachment) || "application/octet-stream") %>" length="<%= size %>"/>
<% else %>
<link rel="enclosure" href="<%= escape(attachment_href(attachment) || "") %>" type="<%= escape(attachment_type(attachment) || "application/octet-stream") %>"/>
<% end %>
<% end %>
<% end %>
<%= if @data["inReplyTo"] do %>
<thr:in-reply-to ref='<%= @data["inReplyTo"] %>' href='<%= get_href(@data["inReplyTo"]) %>'/>
<% end %>
<%= for id <- @activity.recipients do %>
<%= if id == Pleroma.Constants.as_public() do %>
<link rel="mentioned" ostatus:object-type="http://activitystrea.ms/schema/1.0/collection" href="http://activityschema.org/collection/public"/>
<% else %>
<%= unless Regex.match?(~r/^#{Pleroma.Web.Endpoint.url()}.+followers$/, id) do %>
<link rel="mentioned" ostatus:object-type="http://activitystrea.ms/schema/1.0/person" href="<%= id %>"/>
<% end %>
<% end %>
<% end %>
<%= for {emoji, file} <- @data["emoji"] || %{} do %>
<link name="<%= emoji %>" rel="emoji" href="<%= file %>"/>
<% end %>

View file

@ -1,45 +1,34 @@
<item>
<activity:object-type>http://activitystrea.ms/schema/1.0/note</activity:object-type>
<activity:verb>http://activitystrea.ms/schema/1.0/post</activity:verb>
<guid><%= @data["id"] %></guid>
<guid isPermaLink="true"><%= escape(@data["id"] || "") %></guid>
<title><%= activity_title(@data, Keyword.get(@feed_config, :post_title, %{})) %></title>
<description><%= activity_description(@data) %></description>
<content:encoded><![CDATA[<%= rss_content_encoded(@data) %>]]></content:encoded>
<pubDate><%= to_rfc2822(@data["published"]) %></pubDate>
<ostatus:conversation ref="<%= activity_context(@activity) %>">
<%= activity_context(@activity) %>
</ostatus:conversation>
<%= if @activity.local do %>
<link><%= @data["id"] %></link>
<% else %>
<link><%= @data["external_url"] %></link>
<% end %>
<link rel="ostatus:conversation"><%= activity_context(@activity) %></link>
<link><%= escape(activity_link(@activity, @data) || "") %></link>
<%= for tag <- Pleroma.Object.hashtags(@object) do %>
<category term="<%= tag %>"></category>
<%= if tag && tag != "" do %>
<category><%= tag %></category>
<% end %>
<% end %>
<%= unless sensitive?(@data) do %>
<%= with attachment when not is_nil(attachment) <- rss_enclosure_attachment(@data["attachment"]) do %>
<enclosure url="<%= escape(attachment_href(attachment) || "") %>" type="<%= escape(attachment_type(attachment) || "application/octet-stream") %>" length="<%= attachment_size_positive(attachment) %>" />
<% end %>
<% end %>
<%= for attachment <- @data["attachment"] || [] do %>
<enclosure url="<%= attachment_href(attachment) %>" type="<%= attachment_type(attachment) %>" />
<%= media_content_xml(attachment, sensitive?(@data)) %>
<% end %>
<%= if @data["inReplyTo"] do %>
<thr:in-reply-to ref='<%= @data["inReplyTo"] %>' href='<%= get_href(@data["inReplyTo"]) %>'/>
<% end %>
<%= for id <- @activity.recipients do %>
<%= if id == Pleroma.Constants.as_public() do %>
<link rel="mentioned" ostatus:object-type="http://activitystrea.ms/schema/1.0/collection">http://activityschema.org/collection/public</link>
<% else %>
<%= unless Regex.match?(~r/^#{Pleroma.Web.Endpoint.url()}.+followers$/, id) do %>
<link rel="mentioned" ostatus:object-type="http://activitystrea.ms/schema/1.0/person"><%= id %></link>
<% end %>
<% end %>
<% end %>
<%= for {emoji, file} <- @data["emoji"] || %{} do %>
<link name="<%= emoji %>" rel="emoji"><%= file %></link>
<% end %>
</item>

View file

@ -4,9 +4,9 @@
<%= render Phoenix.Controller.view_module(@conn), "_tag_author.atom", assigns %>
<id><%= @data["id"] %></id>
<id><%= escape(@data["id"] || "") %></id>
<title><%= activity_title(@data, Keyword.get(@feed_config, :post_title, %{})) %></title>
<content type="html"><%= activity_description(@data) %></content>
<content type="html"><%= escape(atom_content_encoded(@data)) %></content>
<published><%= to_rfc3339(@data["published"]) %></published>
<updated><%= to_rfc3339(@data["published"]) %></updated>
<ostatus:conversation ref="<%= activity_context(@activity) %>">
@ -15,34 +15,25 @@
<link href="<%= activity_context(@activity) %>" rel="ostatus:conversation"/>
<%= if @data["summary"] != "" do %>
<summary><%= @data["summary"] %></summary>
<summary><%= escape(@data["summary"]) %></summary>
<% end %>
<%= if @activity.local do %>
<link type="application/atom+xml" href='<%= @data["id"] %>' rel="self"/>
<link type="text/html" href='<%= @data["id"] %>' rel="alternate"/>
<% else %>
<link type="text/html" href='<%= @data["external_url"] %>' rel="alternate"/>
<% end %>
<%= for id <- @activity.recipients do %>
<%= if id == Pleroma.Constants.as_public() do %>
<link rel="mentioned"
ostatus:object-type="http://activitystrea.ms/schema/1.0/collection"
href="http://activityschema.org/collection/public"/>
<% else %>
<%= unless Regex.match?(~r/^#{Pleroma.Web.Endpoint.url()}.+followers$/, id) do %>
<link rel="mentioned"
ostatus:object-type="http://activitystrea.ms/schema/1.0/person"
href="<%= id %>" />
<% end %>
<% end %>
<% end %>
<link type="text/html" href='<%= escape(activity_link(@activity, @data) || "") %>' rel="alternate"/>
<%= for tag <- Pleroma.Object.hashtags(@object) do %>
<category term="<%= tag %>"></category>
<% end %>
<%= unless sensitive?(@data) do %>
<%= for attachment <- @data["attachment"] || [] do %>
<%= if size = attachment_size_positive(attachment) do %>
<link rel="enclosure" href="<%= escape(attachment_href(attachment) || "") %>" type="<%= escape(attachment_type(attachment) || "application/octet-stream") %>" length="<%= size %>"/>
<% else %>
<link rel="enclosure" href="<%= escape(attachment_href(attachment) || "") %>" type="<%= escape(attachment_type(attachment) || "application/octet-stream") %>"/>
<% end %>
<% end %>
<% end %>
<%= for {emoji, file} <- @data["emoji"] || %{} do %>
<link name="<%= emoji %>" rel="emoji" href="<%= file %>"/>
<% end %>

View file

@ -1,14 +1,24 @@
<item>
<title><%= activity_title(@data, Keyword.get(@feed_config, :post_title, %{})) %></title>
<guid isPermalink="true"><%= activity_context(@activity) %></guid>
<link><%= activity_context(@activity) %></link>
<guid isPermaLink="true"><%= escape(activity_link(@activity, @data) || "") %></guid>
<link><%= escape(activity_link(@activity, @data) || "") %></link>
<pubDate><%= to_rfc2822(@data["published"]) %></pubDate>
<title><%= activity_title(@data, Keyword.get(@feed_config, :post_title, %{})) %></title>
<description><%= activity_description(@data) %></description>
<%= for attachment <- @data["attachment"] || [] do %>
<enclosure url="<%= attachment_href(attachment) %>" type="<%= attachment_type(attachment) %>"/>
<content:encoded><![CDATA[<%= rss_content_encoded(@data) %>]]></content:encoded>
<%= unless sensitive?(@data) do %>
<%= with attachment when not is_nil(attachment) <- rss_enclosure_attachment(@data["attachment"]) do %>
<enclosure url="<%= escape(attachment_href(attachment) || "") %>" type="<%= escape(attachment_type(attachment) || "application/octet-stream") %>" length="<%= attachment_size_positive(attachment) %>"/>
<% end %>
<% end %>
<%= for attachment <- @data["attachment"] || [] do %>
<%= media_content_xml(attachment, sensitive?(@data)) %>
<% end %>
<%= for tag <- Pleroma.Object.hashtags(@object) do %>
<%= if tag && tag != "" do %>
<category><%= tag %></category>
<% end %>
<% end %>
</item>

View file

@ -9,10 +9,12 @@
<id><%= Routes.tag_feed_url(@conn, :feed, @tag) <> ".atom" %></id>
<title>#<%= @tag %></title>
<subtitle><%= Gettext.dpgettext("static_pages", "tag feed description", "These are public toots tagged with #%{tag}. You can interact with them if you have an account anywhere in the fediverse.", tag: @tag) %></subtitle>
<%= with subtitle when subtitle not in [nil, ""] <- Gettext.dpgettext("static_pages", "tag feed description", "These are public toots tagged with #%{tag}. You can interact with them if you have an account anywhere in the fediverse.", tag: @tag) do %>
<subtitle><%= subtitle %></subtitle>
<% end %>
<logo><%= feed_logo() %></logo>
<updated><%= most_recent_update(@activities) %></updated>
<link rel="self" href="<%= "#{Routes.tag_feed_url(@conn, :feed, @tag)}.atom" %>" type="application/atom+xml"/>
<updated><%= most_recent_update(@activities) || to_rfc3339(NaiveDateTime.utc_now()) %></updated>
<link rel="self" href="<%= feed_self_url(@conn) %>" type="application/atom+xml"/>
<%= for activity <- @activities do %>
<%= render Phoenix.Controller.view_module(@conn), "_tag_activity.atom", Map.merge(assigns, prepare_activity(activity, actor: true)) %>

View file

@ -1,6 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
xmlns:webfeeds="http://webfeeds.org/rss/1.0"
xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:media="http://search.yahoo.com/mrss/"
xmlns:thr="http://purl.org/syndication/thread/1.0">
<channel>
@ -8,7 +10,12 @@
<description><%= Gettext.dpgettext("static_pages", "tag feed description", "These are public toots tagged with #%{tag}. You can interact with them if you have an account anywhere in the fediverse.", tag: @tag) %></description>
<link><%= "#{Routes.tag_feed_url(@conn, :feed, @tag)}.rss" %></link>
<webfeeds:logo><%= feed_logo() %></webfeeds:logo>
<webfeeds:icon><%= feed_logo() %></webfeeds:icon>
<webfeeds:accentColor>2b90d9</webfeeds:accentColor>
<%= with last_build_date when not is_nil(last_build_date) <- most_recent_update(@activities, :rss) do %>
<lastBuildDate><%= last_build_date %></lastBuildDate>
<% end %>
<generator><%= Pleroma.Application.named_version() %></generator>
<%= for activity <- @activities do %>
<%= render Phoenix.Controller.view_module(@conn), "_tag_activity.xml", Map.merge(assigns, prepare_activity(activity)) %>
<% end %>

View file

@ -8,10 +8,12 @@
<id><%= Routes.user_feed_url(@conn, :feed, @user.nickname) <> ".atom" %></id>
<title><%= @user.nickname <> "'s timeline" %></title>
<subtitle><%= escape(@user.bio) %></subtitle>
<%= if @user.bio && @user.bio != "" do %>
<subtitle><%= escape(@user.bio) %></subtitle>
<% end %>
<updated><%= most_recent_update(@activities, @user, :atom) %></updated>
<logo><%= logo(@user) %></logo>
<link rel="self" href="<%= "#{Routes.user_feed_url(@conn, :feed, @user.nickname)}.atom" %>" type="application/atom+xml"/>
<link rel="self" href="<%= feed_self_url(@conn) %>" type="application/atom+xml"/>
<%= render Phoenix.Controller.view_module(@conn), "_author.atom", assigns %>

View file

@ -1,26 +1,32 @@
<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0"
xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:webfeeds="http://webfeeds.org/rss/1.0"
xmlns:media="http://search.yahoo.com/mrss/"
xmlns:thr="http://purl.org/syndication/thread/1.0"
xmlns:activity="http://activitystrea.ms/spec/1.0/"
xmlns:ostatus="http://ostatus.org/schema/1.0"
xmlns:poco="http://portablecontacts.net/spec/1.0">
<channel>
<title><%= @user.nickname <> "'s timeline" %></title>
<link><%= "#{Routes.user_feed_url(@conn, :feed, @user.nickname)}.rss" %></link>
<atom:link href="<%= Routes.user_feed_url(@conn, :feed, @user.nickname) <> ".atom" %>"
<atom:link href="<%= feed_self_url(@conn) %>"
rel="self" type="application/rss+xml" />
<link><%= "#{Routes.user_feed_url(@conn, :feed, @user.nickname)}.rss" %></link>
<description><%= escape(@user.bio) %></description>
<image>
<url><%= logo(@user) %></url>
<title><%= @user.nickname <> "'s timeline" %></title>
<link><%= "#{Routes.user_feed_url(@conn, :feed, @user.nickname)}.rss" %></link>
</image>
<lastBuildDate><%= most_recent_update(@activities, @user, :rss) %></lastBuildDate>
<webfeeds:icon><%= logo(@user) %></webfeeds:icon>
<generator><%= Pleroma.Application.named_version() %></generator>
<%= render Phoenix.Controller.view_module(@conn), "_author.rss", assigns %>
<%= if last_activity(@activities) do %>
<link rel="next"><%= "#{Routes.user_feed_url(@conn, :feed, @user.nickname)}.rss?max_id=#{last_activity(@activities).id}" %></link>
<atom:link rel="next" href="<%= "#{Routes.user_feed_url(@conn, :feed, @user.nickname)}.rss?max_id=#{last_activity(@activities).id}" %>" />
<% end %>
<%= for activity <- @activities do %>