aboutsummaryrefslogtreecommitdiff
path: root/lib/pleroma/web
diff options
context:
space:
mode:
authorEgor Kislitsyn <egor@kislitsyn.com>2019-05-14 18:15:56 +0700
committerEgor Kislitsyn <egor@kislitsyn.com>2019-05-14 18:15:56 +0700
commit5e2b491276d5cd8d90fddf219f7653d1c9b31ef3 (patch)
treec7d10c01a9b17ba9c732cb43e2097bd26d67e915 /lib/pleroma/web
parent1557b99beb3b406572ef2d3baaabed1c9baeca1c (diff)
parentcdcdbd88da76f18c21da7f6f15a29883044902c8 (diff)
downloadpleroma-5e2b491276d5cd8d90fddf219f7653d1c9b31ef3.tar.gz
Merge remote-tracking branch 'pleroma/develop' into feature/disable-account
Diffstat (limited to 'lib/pleroma/web')
-rw-r--r--lib/pleroma/web/activity_pub/activity_pub.ex183
-rw-r--r--lib/pleroma/web/activity_pub/mrf/anti_followbot_policy.ex2
-rw-r--r--lib/pleroma/web/activity_pub/mrf/drop_policy.ex1
-rw-r--r--lib/pleroma/web/activity_pub/mrf/ensure_re_prepended.ex1
-rw-r--r--lib/pleroma/web/activity_pub/mrf/hellthread_policy.ex2
-rw-r--r--lib/pleroma/web/activity_pub/mrf/keyword_policy.ex2
-rw-r--r--lib/pleroma/web/activity_pub/mrf/no_placeholder_text_policy.ex1
-rw-r--r--lib/pleroma/web/activity_pub/mrf/noop_policy.ex1
-rw-r--r--lib/pleroma/web/activity_pub/mrf/normalize_markup.ex1
-rw-r--r--lib/pleroma/web/activity_pub/mrf/reject_non_public.ex1
-rw-r--r--lib/pleroma/web/activity_pub/mrf/simple_policy.ex1
-rw-r--r--lib/pleroma/web/activity_pub/mrf/tag_policy.ex13
-rw-r--r--lib/pleroma/web/activity_pub/mrf/user_allowlist.ex1
-rw-r--r--lib/pleroma/web/activity_pub/publisher.ex152
-rw-r--r--lib/pleroma/web/activity_pub/utils.ex2
-rw-r--r--lib/pleroma/web/admin_api/admin_api_controller.ex11
-rw-r--r--lib/pleroma/web/admin_api/search.ex44
-rw-r--r--lib/pleroma/web/auth/pleroma_authenticator.ex2
-rw-r--r--lib/pleroma/web/controller_helper.ex6
-rw-r--r--lib/pleroma/web/endpoint.ex7
-rw-r--r--lib/pleroma/web/federator/federator.ex51
-rw-r--r--lib/pleroma/web/federator/publisher.ex95
-rw-r--r--lib/pleroma/web/mastodon_api/mastodon_api_controller.ex117
-rw-r--r--lib/pleroma/web/mastodon_api/views/conversation_view.ex38
-rw-r--r--lib/pleroma/web/mastodon_api/views/status_view.ex18
-rw-r--r--lib/pleroma/web/nodeinfo/nodeinfo_controller.ex3
-rw-r--r--lib/pleroma/web/oauth.ex14
-rw-r--r--lib/pleroma/web/oauth/app.ex1
-rw-r--r--lib/pleroma/web/oauth/authorization.ex39
-rw-r--r--lib/pleroma/web/oauth/oauth_controller.ex57
-rw-r--r--lib/pleroma/web/oauth/scopes.ex67
-rw-r--r--lib/pleroma/web/oauth/token.ex11
-rw-r--r--lib/pleroma/web/ostatus/activity_representer.ex21
-rw-r--r--lib/pleroma/web/ostatus/ostatus.ex3
-rw-r--r--lib/pleroma/web/router.ex45
-rw-r--r--lib/pleroma/web/salmon/salmon.ex50
-rw-r--r--lib/pleroma/web/streamer.ex29
-rw-r--r--lib/pleroma/web/twitter_api/twitter_api.ex29
-rw-r--r--lib/pleroma/web/twitter_api/twitter_api_controller.ex3
-rw-r--r--lib/pleroma/web/twitter_api/views/activity_view.ex2
-rw-r--r--lib/pleroma/web/web_finger/web_finger.ex66
-rw-r--r--lib/pleroma/web/websub/websub.ex33
42 files changed, 849 insertions, 377 deletions
diff --git a/lib/pleroma/web/activity_pub/activity_pub.ex b/lib/pleroma/web/activity_pub/activity_pub.ex
index d06bc64ea..9a137d8de 100644
--- a/lib/pleroma/web/activity_pub/activity_pub.ex
+++ b/lib/pleroma/web/activity_pub/activity_pub.ex
@@ -4,7 +4,7 @@
defmodule Pleroma.Web.ActivityPub.ActivityPub do
alias Pleroma.Activity
- alias Pleroma.Instances
+ alias Pleroma.Conversation
alias Pleroma.Notification
alias Pleroma.Object
alias Pleroma.Object.Fetcher
@@ -14,7 +14,6 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do
alias Pleroma.User
alias Pleroma.Web.ActivityPub.MRF
alias Pleroma.Web.ActivityPub.Transmogrifier
- alias Pleroma.Web.Federator
alias Pleroma.Web.WebFinger
import Ecto.Query
@@ -23,8 +22,6 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do
require Logger
- @httpoison Application.get_env(:pleroma, :httpoison)
-
# For Announce activities, we filter the recipients based on following status for any actors
# that match actual users. See issue #164 for more information about why this is necessary.
defp get_recipients(%{"type" => "Announce"} = data) do
@@ -141,7 +138,14 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do
end)
Notification.create_notifications(activity)
+
+ participations =
+ activity
+ |> Conversation.create_or_bump_for()
+ |> get_participations()
+
stream_out(activity)
+ stream_out_participations(participations)
{:ok, activity}
else
%Activity{} = activity ->
@@ -164,6 +168,19 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do
end
end
+ defp get_participations({:ok, %{participations: participations}}), do: participations
+ defp get_participations(_), do: []
+
+ def stream_out_participations(participations) do
+ participations =
+ participations
+ |> Repo.preload(:user)
+
+ Enum.each(participations, fn participation ->
+ Pleroma.Web.Streamer.stream("participation", participation)
+ end)
+ end
+
def stream_out(activity) do
public = "https://www.w3.org/ns/activitystreams#Public"
@@ -195,6 +212,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do
end
end
else
+ # TODO: Write test, replace with visibility test
if !Enum.member?(activity.data["cc"] || [], public) &&
!Enum.member?(
activity.data["to"],
@@ -457,35 +475,44 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do
end
end
- def fetch_activities_for_context(context, opts \\ %{}) do
+ defp fetch_activities_for_context_query(context, opts) do
public = ["https://www.w3.org/ns/activitystreams#Public"]
recipients =
if opts["user"], do: [opts["user"].ap_id | opts["user"].following] ++ public, else: public
- query = from(activity in Activity)
-
- query =
- query
- |> restrict_blocked(opts)
- |> restrict_recipients(recipients, opts["user"])
-
- query =
- from(
- activity in query,
- where:
- fragment(
- "?->>'type' = ? and ?->>'context' = ?",
- activity.data,
- "Create",
- activity.data,
- ^context
- ),
- order_by: [desc: :id]
+ from(activity in Activity)
+ |> restrict_blocked(opts)
+ |> restrict_recipients(recipients, opts["user"])
+ |> where(
+ [activity],
+ fragment(
+ "?->>'type' = ? and ?->>'context' = ?",
+ activity.data,
+ "Create",
+ activity.data,
+ ^context
)
- |> Activity.with_preloaded_object()
+ )
+ |> order_by([activity], desc: activity.id)
+ end
- Repo.all(query)
+ @spec fetch_activities_for_context(String.t(), keyword() | map()) :: [Activity.t()]
+ def fetch_activities_for_context(context, opts \\ %{}) do
+ context
+ |> fetch_activities_for_context_query(opts)
+ |> Activity.with_preloaded_object()
+ |> Repo.all()
+ end
+
+ @spec fetch_latest_activity_id_for_context(String.t(), keyword() | map()) ::
+ Pleroma.FlakeId.t() | nil
+ def fetch_latest_activity_id_for_context(context, opts \\ %{}) do
+ context
+ |> fetch_activities_for_context_query(opts)
+ |> limit(1)
+ |> select([a], a.id)
+ |> Repo.one()
end
def fetch_public_activities(opts \\ %{}) do
@@ -784,11 +811,32 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do
|> Activity.with_preloaded_object()
end
+ defp maybe_preload_bookmarks(query, %{"skip_preload" => true}), do: query
+
+ defp maybe_preload_bookmarks(query, opts) do
+ query
+ |> Activity.with_preloaded_bookmark(opts["user"])
+ end
+
+ defp maybe_order(query, %{order: :desc}) do
+ query
+ |> order_by(desc: :id)
+ end
+
+ defp maybe_order(query, %{order: :asc}) do
+ query
+ |> order_by(asc: :id)
+ end
+
+ defp maybe_order(query, _), do: query
+
def fetch_activities_query(recipients, opts \\ %{}) do
base_query = from(activity in Activity)
base_query
|> maybe_preload_objects(opts)
+ |> maybe_preload_bookmarks(opts)
+ |> maybe_order(opts)
|> restrict_recipients(recipients, opts["user"])
|> restrict_tag(opts)
|> restrict_tag_reject(opts)
@@ -910,89 +958,6 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do
end
end
- def should_federate?(inbox, public) do
- if public do
- true
- else
- inbox_info = URI.parse(inbox)
- !Enum.member?(Pleroma.Config.get([:instance, :quarantined_instances], []), inbox_info.host)
- end
- end
-
- def publish(actor, activity) do
- remote_followers =
- if actor.follower_address in activity.recipients do
- {:ok, followers} = User.get_followers(actor)
- followers |> Enum.filter(&(!&1.local))
- else
- []
- end
-
- public = is_public?(activity)
-
- {:ok, data} = Transmogrifier.prepare_outgoing(activity.data)
- json = Jason.encode!(data)
-
- (Pleroma.Web.Salmon.remote_users(activity) ++ remote_followers)
- |> Enum.filter(fn user -> User.ap_enabled?(user) end)
- |> Enum.map(fn %{info: %{source_data: data}} ->
- (is_map(data["endpoints"]) && Map.get(data["endpoints"], "sharedInbox")) || data["inbox"]
- end)
- |> Enum.uniq()
- |> Enum.filter(fn inbox -> should_federate?(inbox, public) end)
- |> Instances.filter_reachable()
- |> Enum.each(fn {inbox, unreachable_since} ->
- Federator.publish_single_ap(%{
- inbox: inbox,
- json: json,
- actor: actor,
- id: activity.data["id"],
- unreachable_since: unreachable_since
- })
- end)
- end
-
- def publish_one(%{inbox: inbox, json: json, actor: actor, id: id} = params) do
- Logger.info("Federating #{id} to #{inbox}")
- host = URI.parse(inbox).host
-
- digest = "SHA-256=" <> (:crypto.hash(:sha256, json) |> Base.encode64())
-
- date =
- NaiveDateTime.utc_now()
- |> Timex.format!("{WDshort}, {0D} {Mshort} {YYYY} {h24}:{m}:{s} GMT")
-
- signature =
- Pleroma.Web.HTTPSignatures.sign(actor, %{
- host: host,
- "content-length": byte_size(json),
- digest: digest,
- date: date
- })
-
- with {:ok, %{status: code}} when code in 200..299 <-
- result =
- @httpoison.post(
- inbox,
- json,
- [
- {"Content-Type", "application/activity+json"},
- {"Date", date},
- {"signature", signature},
- {"digest", digest}
- ]
- ) do
- if !Map.has_key?(params, :unreachable_since) || params[:unreachable_since],
- do: Instances.set_reachable(inbox)
-
- result
- else
- {_post_result, response} ->
- unless params[:unreachable_since], do: Instances.set_unreachable(inbox)
- {:error, response}
- end
- end
-
# filter out broken threads
def contain_broken_threads(%Activity{} = activity, %User{} = user) do
entire_thread_visible_for_user?(activity, user)
diff --git a/lib/pleroma/web/activity_pub/mrf/anti_followbot_policy.ex b/lib/pleroma/web/activity_pub/mrf/anti_followbot_policy.ex
index 34665a3a6..87fa514c3 100644
--- a/lib/pleroma/web/activity_pub/mrf/anti_followbot_policy.ex
+++ b/lib/pleroma/web/activity_pub/mrf/anti_followbot_policy.ex
@@ -5,6 +5,8 @@
defmodule Pleroma.Web.ActivityPub.MRF.AntiFollowbotPolicy do
alias Pleroma.User
+ @moduledoc "Prevent followbots from following with a bit of heuristic"
+
@behaviour Pleroma.Web.ActivityPub.MRF
# XXX: this should become User.normalize_by_ap_id() or similar, really.
diff --git a/lib/pleroma/web/activity_pub/mrf/drop_policy.ex b/lib/pleroma/web/activity_pub/mrf/drop_policy.ex
index a93ccf386..b8d38aae6 100644
--- a/lib/pleroma/web/activity_pub/mrf/drop_policy.ex
+++ b/lib/pleroma/web/activity_pub/mrf/drop_policy.ex
@@ -4,6 +4,7 @@
defmodule Pleroma.Web.ActivityPub.MRF.DropPolicy do
require Logger
+ @moduledoc "Drop and log everything received"
@behaviour Pleroma.Web.ActivityPub.MRF
@impl true
diff --git a/lib/pleroma/web/activity_pub/mrf/ensure_re_prepended.ex b/lib/pleroma/web/activity_pub/mrf/ensure_re_prepended.ex
index 895376c9d..15d8514be 100644
--- a/lib/pleroma/web/activity_pub/mrf/ensure_re_prepended.ex
+++ b/lib/pleroma/web/activity_pub/mrf/ensure_re_prepended.ex
@@ -5,6 +5,7 @@
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
@reply_prefix Regex.compile!("^re:[[:space:]]*", [:caseless])
diff --git a/lib/pleroma/web/activity_pub/mrf/hellthread_policy.ex b/lib/pleroma/web/activity_pub/mrf/hellthread_policy.ex
index 6736f3cb9..a699f6a7e 100644
--- a/lib/pleroma/web/activity_pub/mrf/hellthread_policy.ex
+++ b/lib/pleroma/web/activity_pub/mrf/hellthread_policy.ex
@@ -4,6 +4,8 @@
defmodule Pleroma.Web.ActivityPub.MRF.HellthreadPolicy do
alias Pleroma.User
+ @moduledoc "Block messages with too much mentions (configurable)"
+
@behaviour Pleroma.Web.ActivityPub.MRF
defp delist_message(message, threshold) when threshold > 0 do
diff --git a/lib/pleroma/web/activity_pub/mrf/keyword_policy.ex b/lib/pleroma/web/activity_pub/mrf/keyword_policy.ex
index e8dfba672..d5c341433 100644
--- a/lib/pleroma/web/activity_pub/mrf/keyword_policy.ex
+++ b/lib/pleroma/web/activity_pub/mrf/keyword_policy.ex
@@ -3,6 +3,8 @@
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.ActivityPub.MRF.KeywordPolicy do
+ @moduledoc "Reject or Word-Replace messages with a keyword or regex"
+
@behaviour Pleroma.Web.ActivityPub.MRF
defp string_matches?(string, _) when not is_binary(string) do
false
diff --git a/lib/pleroma/web/activity_pub/mrf/no_placeholder_text_policy.ex b/lib/pleroma/web/activity_pub/mrf/no_placeholder_text_policy.ex
index 081456046..f30fee0d5 100644
--- a/lib/pleroma/web/activity_pub/mrf/no_placeholder_text_policy.ex
+++ b/lib/pleroma/web/activity_pub/mrf/no_placeholder_text_policy.ex
@@ -3,6 +3,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
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
@impl true
diff --git a/lib/pleroma/web/activity_pub/mrf/noop_policy.ex b/lib/pleroma/web/activity_pub/mrf/noop_policy.ex
index 40f37bdb1..c47cb3298 100644
--- a/lib/pleroma/web/activity_pub/mrf/noop_policy.ex
+++ b/lib/pleroma/web/activity_pub/mrf/noop_policy.ex
@@ -3,6 +3,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.ActivityPub.MRF.NoOpPolicy do
+ @moduledoc "Does nothing (lets the messages go through unmodified)"
@behaviour Pleroma.Web.ActivityPub.MRF
@impl true
diff --git a/lib/pleroma/web/activity_pub/mrf/normalize_markup.ex b/lib/pleroma/web/activity_pub/mrf/normalize_markup.ex
index 3d13cdb32..9c87c6963 100644
--- a/lib/pleroma/web/activity_pub/mrf/normalize_markup.ex
+++ b/lib/pleroma/web/activity_pub/mrf/normalize_markup.ex
@@ -3,6 +3,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.ActivityPub.MRF.NormalizeMarkup do
+ @moduledoc "Scrub configured hypertext markup"
alias Pleroma.HTML
@behaviour Pleroma.Web.ActivityPub.MRF
diff --git a/lib/pleroma/web/activity_pub/mrf/reject_non_public.ex b/lib/pleroma/web/activity_pub/mrf/reject_non_public.ex
index 4197be847..ea3df1b4d 100644
--- a/lib/pleroma/web/activity_pub/mrf/reject_non_public.ex
+++ b/lib/pleroma/web/activity_pub/mrf/reject_non_public.ex
@@ -4,6 +4,7 @@
defmodule Pleroma.Web.ActivityPub.MRF.RejectNonPublic do
alias Pleroma.User
+ @moduledoc "Rejects non-public (followers-only, direct) activities"
@behaviour Pleroma.Web.ActivityPub.MRF
@impl true
diff --git a/lib/pleroma/web/activity_pub/mrf/simple_policy.ex b/lib/pleroma/web/activity_pub/mrf/simple_policy.ex
index 798ba9687..2f105700b 100644
--- a/lib/pleroma/web/activity_pub/mrf/simple_policy.ex
+++ b/lib/pleroma/web/activity_pub/mrf/simple_policy.ex
@@ -4,6 +4,7 @@
defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicy do
alias Pleroma.User
+ @moduledoc "Filter activities depending on their origin instance"
@behaviour Pleroma.Web.ActivityPub.MRF
defp check_accept(%{host: actor_host} = _actor_info, object) do
diff --git a/lib/pleroma/web/activity_pub/mrf/tag_policy.ex b/lib/pleroma/web/activity_pub/mrf/tag_policy.ex
index b242e44e6..b52be30e7 100644
--- a/lib/pleroma/web/activity_pub/mrf/tag_policy.ex
+++ b/lib/pleroma/web/activity_pub/mrf/tag_policy.ex
@@ -5,6 +5,19 @@
defmodule Pleroma.Web.ActivityPub.MRF.TagPolicy do
alias Pleroma.User
@behaviour Pleroma.Web.ActivityPub.MRF
+ @moduledoc """
+ Apply policies based on user tags
+
+ This policy applies policies on a user activities depending on their tags
+ on your instance.
+
+ - `mrf_tag:media-force-nsfw`: Mark as sensitive on presence of attachments
+ - `mrf_tag:media-strip`: Remove attachments
+ - `mrf_tag:force-unlisted`: Mark as unlisted (removes from the federated timeline)
+ - `mrf_tag:sandbox`: Remove from public (local and federated) timelines
+ - `mrf_tag:disable-remote-subscription`: Reject non-local follow requests
+ - `mrf_tag:disable-any-subscription`: Reject any follow requests
+ """
defp get_tags(%User{tags: tags}) when is_list(tags), do: tags
defp get_tags(_), do: []
diff --git a/lib/pleroma/web/activity_pub/mrf/user_allowlist.ex b/lib/pleroma/web/activity_pub/mrf/user_allowlist.ex
index a3b1f8aa0..f5078d818 100644
--- a/lib/pleroma/web/activity_pub/mrf/user_allowlist.ex
+++ b/lib/pleroma/web/activity_pub/mrf/user_allowlist.ex
@@ -5,6 +5,7 @@
defmodule Pleroma.Web.ActivityPub.MRF.UserAllowListPolicy do
alias Pleroma.Config
+ @moduledoc "Accept-list of users from specified instances"
@behaviour Pleroma.Web.ActivityPub.MRF
defp filter_by_list(object, []), do: {:ok, object}
diff --git a/lib/pleroma/web/activity_pub/publisher.ex b/lib/pleroma/web/activity_pub/publisher.ex
new file mode 100644
index 000000000..8e3af0a81
--- /dev/null
+++ b/lib/pleroma/web/activity_pub/publisher.ex
@@ -0,0 +1,152 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.Web.ActivityPub.Publisher do
+ alias Pleroma.Activity
+ alias Pleroma.Config
+ alias Pleroma.Instances
+ alias Pleroma.User
+ alias Pleroma.Web.ActivityPub.Relay
+ alias Pleroma.Web.ActivityPub.Transmogrifier
+
+ import Pleroma.Web.ActivityPub.Visibility
+
+ @behaviour Pleroma.Web.Federator.Publisher
+
+ require Logger
+
+ @httpoison Application.get_env(:pleroma, :httpoison)
+
+ @moduledoc """
+ ActivityPub outgoing federation module.
+ """
+
+ @doc """
+ Determine if an activity can be represented by running it through Transmogrifier.
+ """
+ def is_representable?(%Activity{} = activity) do
+ with {:ok, _data} <- Transmogrifier.prepare_outgoing(activity.data) do
+ true
+ else
+ _e ->
+ false
+ end
+ end
+
+ @doc """
+ Publish a single message to a peer. Takes a struct with the following
+ parameters set:
+
+ * `inbox`: the inbox to publish to
+ * `json`: the JSON message body representing the ActivityPub message
+ * `actor`: the actor which is signing the message
+ * `id`: the ActivityStreams URI of the message
+ """
+ def publish_one(%{inbox: inbox, json: json, actor: %User{} = actor, id: id} = params) do
+ Logger.info("Federating #{id} to #{inbox}")
+ host = URI.parse(inbox).host
+
+ digest = "SHA-256=" <> (:crypto.hash(:sha256, json) |> Base.encode64())
+
+ date =
+ NaiveDateTime.utc_now()
+ |> Timex.format!("{WDshort}, {0D} {Mshort} {YYYY} {h24}:{m}:{s} GMT")
+
+ signature =
+ Pleroma.Web.HTTPSignatures.sign(actor, %{
+ host: host,
+ "content-length": byte_size(json),
+ digest: digest,
+ date: date
+ })
+
+ with {:ok, %{status: code}} when code in 200..299 <-
+ result =
+ @httpoison.post(
+ inbox,
+ json,
+ [
+ {"Content-Type", "application/activity+json"},
+ {"Date", date},
+ {"signature", signature},
+ {"digest", digest}
+ ]
+ ) do
+ if !Map.has_key?(params, :unreachable_since) || params[:unreachable_since],
+ do: Instances.set_reachable(inbox)
+
+ result
+ else
+ {_post_result, response} ->
+ unless params[:unreachable_since], do: Instances.set_unreachable(inbox)
+ {:error, response}
+ end
+ end
+
+ defp should_federate?(inbox, public) do
+ if public do
+ true
+ else
+ inbox_info = URI.parse(inbox)
+ !Enum.member?(Pleroma.Config.get([:instance, :quarantined_instances], []), inbox_info.host)
+ end
+ end
+
+ @doc """
+ Publishes an activity to all relevant peers.
+ """
+ def publish(%User{} = actor, %Activity{} = activity) do
+ remote_followers =
+ if actor.follower_address in activity.recipients do
+ {:ok, followers} = User.get_followers(actor)
+ followers |> Enum.filter(&(!&1.local))
+ else
+ []
+ end
+
+ public = is_public?(activity)
+
+ if public && Config.get([:instance, :allow_relay]) do
+ Logger.info(fn -> "Relaying #{activity.data["id"]} out" end)
+ Relay.publish(activity)
+ end
+
+ {:ok, data} = Transmogrifier.prepare_outgoing(activity.data)
+ json = Jason.encode!(data)
+
+ (Pleroma.Web.Salmon.remote_users(activity) ++ remote_followers)
+ |> Enum.filter(fn user -> User.ap_enabled?(user) end)
+ |> Enum.map(fn %{info: %{source_data: data}} ->
+ (is_map(data["endpoints"]) && Map.get(data["endpoints"], "sharedInbox")) || data["inbox"]
+ end)
+ |> Enum.uniq()
+ |> Enum.filter(fn inbox -> should_federate?(inbox, public) end)
+ |> Instances.filter_reachable()
+ |> Enum.each(fn {inbox, unreachable_since} ->
+ Pleroma.Web.Federator.Publisher.enqueue_one(
+ __MODULE__,
+ %{
+ inbox: inbox,
+ json: json,
+ actor: actor,
+ id: activity.data["id"],
+ unreachable_since: unreachable_since
+ }
+ )
+ end)
+ end
+
+ def gather_webfinger_links(%User{} = user) do
+ [
+ %{"rel" => "self", "type" => "application/activity+json", "href" => user.ap_id},
+ %{
+ "rel" => "self",
+ "type" => "application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\"",
+ "href" => user.ap_id
+ }
+ ]
+ end
+
+ def gather_nodeinfo_protocol_names, do: ["activitypub"]
+end
diff --git a/lib/pleroma/web/activity_pub/utils.ex b/lib/pleroma/web/activity_pub/utils.ex
index 581b9d1ab..236d1b4ac 100644
--- a/lib/pleroma/web/activity_pub/utils.ex
+++ b/lib/pleroma/web/activity_pub/utils.ex
@@ -682,7 +682,7 @@ defmodule Pleroma.Web.ActivityPub.Utils do
"""
def fetch_ordered_collection(from, pages_left, acc \\ []) do
with {:ok, response} <- Tesla.get(from),
- {:ok, collection} <- Poison.decode(response.body) do
+ {:ok, collection} <- Jason.decode(response.body) do
case collection["type"] do
"OrderedCollection" ->
# If we've encountered the OrderedCollection and not the page,
diff --git a/lib/pleroma/web/admin_api/admin_api_controller.ex b/lib/pleroma/web/admin_api/admin_api_controller.ex
index 711f233a6..e00b33aba 100644
--- a/lib/pleroma/web/admin_api/admin_api_controller.ex
+++ b/lib/pleroma/web/admin_api/admin_api_controller.ex
@@ -59,7 +59,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIController do
bio: "."
}
- changeset = User.register_changeset(%User{}, user_data, confirmed: true)
+ changeset = User.register_changeset(%User{}, user_data, need_confirmation: false)
{:ok, user} = User.register(changeset)
conn
@@ -101,7 +101,10 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIController do
search_params = %{
query: params["query"],
page: page,
- page_size: page_size
+ page_size: page_size,
+ tags: params["tags"],
+ name: params["name"],
+ email: params["email"]
}
with {:ok, users, count} <- Search.user(Map.merge(search_params, filters)),
@@ -116,11 +119,11 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIController do
)
end
- @filters ~w(local external active deactivated)
+ @filters ~w(local external active deactivated is_admin is_moderator)
+ @spec maybe_parse_filters(String.t()) :: %{required(String.t()) => true} | %{}
defp maybe_parse_filters(filters) when is_nil(filters) or filters == "", do: %{}
- @spec maybe_parse_filters(String.t()) :: %{required(String.t()) => true} | %{}
defp maybe_parse_filters(filters) do
filters
|> String.split(",")
diff --git a/lib/pleroma/web/admin_api/search.ex b/lib/pleroma/web/admin_api/search.ex
index 9a8e41c2a..ed919833e 100644
--- a/lib/pleroma/web/admin_api/search.ex
+++ b/lib/pleroma/web/admin_api/search.ex
@@ -10,45 +10,23 @@ defmodule Pleroma.Web.AdminAPI.Search do
@page_size 50
- def user(%{query: term} = params) when is_nil(term) or term == "" do
- query = maybe_filtered_query(params)
+ defmacro not_empty_string(string) do
+ quote do
+ is_binary(unquote(string)) and unquote(string) != ""
+ end
+ end
+
+ @spec user(map()) :: {:ok, [User.t()], pos_integer()}
+ def user(params \\ %{}) do
+ query = User.Query.build(params) |> order_by([u], u.nickname)
paginated_query =
- maybe_filtered_query(params)
- |> paginate(params[:page] || 1, params[:page_size] || @page_size)
+ User.Query.paginate(query, params[:page] || 1, params[:page_size] || @page_size)
- count = query |> Repo.aggregate(:count, :id)
+ count = Repo.aggregate(query, :count, :id)
results = Repo.all(paginated_query)
{:ok, results, count}
end
-
- def user(%{query: term} = params) when is_binary(term) do
- search_query = from(u in maybe_filtered_query(params), where: ilike(u.nickname, ^"%#{term}%"))
-
- count = search_query |> Repo.aggregate(:count, :id)
-
- results =
- search_query
- |> paginate(params[:page] || 1, params[:page_size] || @page_size)
- |> Repo.all()
-
- {:ok, results, count}
- end
-
- defp maybe_filtered_query(params) do
- from(u in User, order_by: u.nickname)
- |> User.maybe_local_user_query(params[:local])
- |> User.maybe_external_user_query(params[:external])
- |> User.maybe_active_user_query(params[:active])
- |> User.maybe_deactivated_user_query(params[:deactivated])
- end
-
- defp paginate(query, page, page_size) do
- from(u in query,
- limit: ^page_size,
- offset: ^((page - 1) * page_size)
- )
- end
end
diff --git a/lib/pleroma/web/auth/pleroma_authenticator.ex b/lib/pleroma/web/auth/pleroma_authenticator.ex
index dd79cdcf7..c4a6fce08 100644
--- a/lib/pleroma/web/auth/pleroma_authenticator.ex
+++ b/lib/pleroma/web/auth/pleroma_authenticator.ex
@@ -74,7 +74,7 @@ defmodule Pleroma.Web.Auth.PleromaAuthenticator do
password_confirmation: random_password
},
external: true,
- confirmed: true
+ need_confirmation: false
)
|> Repo.insert(),
{:ok, _} <-
diff --git a/lib/pleroma/web/controller_helper.ex b/lib/pleroma/web/controller_helper.ex
index 181483664..55706eeb8 100644
--- a/lib/pleroma/web/controller_helper.ex
+++ b/lib/pleroma/web/controller_helper.ex
@@ -10,12 +10,6 @@ defmodule Pleroma.Web.ControllerHelper do
def truthy_param?(blank_value) when blank_value in [nil, ""], do: nil
def truthy_param?(value), do: value not in @falsy_param_values
- def oauth_scopes(params, default) do
- # Note: `scopes` is used by Mastodon — supporting it but sticking to
- # OAuth's standard `scope` wherever we control it
- Pleroma.Web.OAuth.parse_scopes(params["scope"] || params["scopes"], default)
- end
-
def json_response(conn, status, json) do
conn
|> put_status(status)
diff --git a/lib/pleroma/web/endpoint.ex b/lib/pleroma/web/endpoint.ex
index 7f939991d..9ef30e885 100644
--- a/lib/pleroma/web/endpoint.ex
+++ b/lib/pleroma/web/endpoint.ex
@@ -29,6 +29,13 @@ defmodule Pleroma.Web.Endpoint do
# credo:disable-for-previous-line Credo.Check.Readability.MaxLineLength
)
+ plug(Plug.Static.IndexHtml, at: "/pleroma/admin/")
+
+ plug(Plug.Static,
+ at: "/pleroma/admin/",
+ from: {:pleroma, "priv/static/adminfe/"}
+ )
+
# Code reloading can be explicitly enabled under the
# :code_reloader configuration of your endpoint.
if code_reloading? do
diff --git a/lib/pleroma/web/federator/federator.ex b/lib/pleroma/web/federator/federator.ex
index 29e178ba9..169fdf4dc 100644
--- a/lib/pleroma/web/federator/federator.ex
+++ b/lib/pleroma/web/federator/federator.ex
@@ -7,13 +7,10 @@ defmodule Pleroma.Web.Federator do
alias Pleroma.Object.Containment
alias Pleroma.User
alias Pleroma.Web.ActivityPub.ActivityPub
- alias Pleroma.Web.ActivityPub.Relay
alias Pleroma.Web.ActivityPub.Transmogrifier
alias Pleroma.Web.ActivityPub.Utils
- alias Pleroma.Web.ActivityPub.Visibility
+ alias Pleroma.Web.Federator.Publisher
alias Pleroma.Web.Federator.RetryQueue
- alias Pleroma.Web.OStatus
- alias Pleroma.Web.Salmon
alias Pleroma.Web.WebFinger
alias Pleroma.Web.Websub
@@ -42,14 +39,6 @@ defmodule Pleroma.Web.Federator do
PleromaJobQueue.enqueue(:federator_outgoing, __MODULE__, [:publish, activity], priority)
end
- def publish_single_ap(params) do
- PleromaJobQueue.enqueue(:federator_outgoing, __MODULE__, [:publish_single_ap, params])
- end
-
- def publish_single_websub(websub) do
- PleromaJobQueue.enqueue(:federator_outgoing, __MODULE__, [:publish_single_websub, websub])
- end
-
def verify_websub(websub) do
PleromaJobQueue.enqueue(:federator_outgoing, __MODULE__, [:verify_websub, websub])
end
@@ -62,10 +51,6 @@ defmodule Pleroma.Web.Federator do
PleromaJobQueue.enqueue(:federator_outgoing, __MODULE__, [:refresh_subscriptions])
end
- def publish_single_salmon(params) do
- PleromaJobQueue.enqueue(:federator_outgoing, __MODULE__, [:publish_single_salmon, params])
- end
-
# Job Worker Callbacks
def perform(:refresh_subscriptions) do
@@ -95,23 +80,7 @@ defmodule Pleroma.Web.Federator do
with actor when not is_nil(actor) <- User.get_cached_by_ap_id(activity.data["actor"]) do
{:ok, actor} = WebFinger.ensure_keys_present(actor)
- if Visibility.is_public?(activity) do
- if OStatus.is_representable?(activity) do
- Logger.info(fn -> "Sending #{activity.data["id"]} out via WebSub" end)
- Websub.publish(Pleroma.Web.OStatus.feed_path(actor), actor, activity)
-
- Logger.info(fn -> "Sending #{activity.data["id"]} out via Salmon" end)
- Pleroma.Web.Salmon.publish(actor, activity)
- end
-
- if Keyword.get(Application.get_env(:pleroma, :instance), :allow_relay) do
- Logger.info(fn -> "Relaying #{activity.data["id"]} out" end)
- Relay.publish(activity)
- end
- end
-
- Logger.info(fn -> "Sending #{activity.data["id"]} out via AP" end)
- Pleroma.Web.ActivityPub.ActivityPub.publish(actor, activity)
+ Publisher.publish(actor, activity)
end
end
@@ -148,25 +117,11 @@ defmodule Pleroma.Web.Federator do
_e ->
# Just drop those for now
Logger.info("Unhandled activity")
- Logger.info(Poison.encode!(params, pretty: 2))
+ Logger.info(Jason.encode!(params, pretty: true))
:error
end
end
- def perform(:publish_single_salmon, params) do
- Salmon.send_to_user(params)
- end
-
- def perform(:publish_single_ap, params) do
- case ActivityPub.publish_one(params) do
- {:ok, _} ->
- :ok
-
- {:error, _} ->
- RetryQueue.enqueue(params, ActivityPub)
- end
- end
-
def perform(
:publish_single_websub,
%{xml: _xml, topic: _topic, callback: _callback, secret: _secret} = params
diff --git a/lib/pleroma/web/federator/publisher.ex b/lib/pleroma/web/federator/publisher.ex
new file mode 100644
index 000000000..916bcdcba
--- /dev/null
+++ b/lib/pleroma/web/federator/publisher.ex
@@ -0,0 +1,95 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.Web.Federator.Publisher do
+ alias Pleroma.Activity
+ alias Pleroma.Config
+ alias Pleroma.User
+ alias Pleroma.Web.Federator.RetryQueue
+
+ require Logger
+
+ @moduledoc """
+ Defines the contract used by federation implementations to publish messages to
+ their peers.
+ """
+
+ @doc """
+ Determine whether an activity can be relayed using the federation module.
+ """
+ @callback is_representable?(Pleroma.Activity.t()) :: boolean()
+
+ @doc """
+ Relays an activity to a specified peer, determined by the parameters. The
+ parameters used are controlled by the federation module.
+ """
+ @callback publish_one(Map.t()) :: {:ok, Map.t()} | {:error, any()}
+
+ @doc """
+ Enqueue publishing a single activity.
+ """
+ @spec enqueue_one(module(), Map.t()) :: :ok
+ def enqueue_one(module, %{} = params),
+ do: PleromaJobQueue.enqueue(:federation_outgoing, __MODULE__, [:publish_one, module, params])
+
+ @spec perform(atom(), module(), any()) :: {:ok, any()} | {:error, any()}
+ def perform(:publish_one, module, params) do
+ case apply(module, :publish_one, [params]) do
+ {:ok, _} ->
+ :ok
+
+ {:error, _e} ->
+ RetryQueue.enqueue(params, module)
+ end
+ end
+
+ def perform(type, _, _) do
+ Logger.debug("Unknown task: #{type}")
+ {:error, "Don't know what to do with this"}
+ end
+
+ @doc """
+ Relays an activity to all specified peers.
+ """
+ @callback publish(Pleroma.User.t(), Pleroma.Activity.t()) :: :ok | {:error, any()}
+
+ @spec publish(Pleroma.User.t(), Pleroma.Activity.t()) :: :ok
+ def publish(%User{} = user, %Activity{} = activity) do
+ Config.get([:instance, :federation_publisher_modules])
+ |> Enum.each(fn module ->
+ if module.is_representable?(activity) do
+ Logger.info("Publishing #{activity.data["id"]} using #{inspect(module)}")
+ module.publish(user, activity)
+ end
+ end)
+
+ :ok
+ end
+
+ @doc """
+ Gathers links used by an outgoing federation module for WebFinger output.
+ """
+ @callback gather_webfinger_links(Pleroma.User.t()) :: list()
+
+ @spec gather_webfinger_links(Pleroma.User.t()) :: list()
+ def gather_webfinger_links(%User{} = user) do
+ Config.get([:instance, :federation_publisher_modules])
+ |> Enum.reduce([], fn module, links ->
+ links ++ module.gather_webfinger_links(user)
+ end)
+ end
+
+ @doc """
+ Gathers nodeinfo protocol names supported by the federation module.
+ """
+ @callback gather_nodeinfo_protocol_names() :: list()
+
+ @spec gather_nodeinfo_protocol_names() :: list()
+ def gather_nodeinfo_protocol_names do
+ Config.get([:instance, :federation_publisher_modules])
+ |> Enum.reduce([], fn module, links ->
+ links ++ module.gather_nodeinfo_protocol_names()
+ end)
+ end
+end
diff --git a/lib/pleroma/web/mastodon_api/mastodon_api_controller.ex b/lib/pleroma/web/mastodon_api/mastodon_api_controller.ex
index b099199af..87e597074 100644
--- a/lib/pleroma/web/mastodon_api/mastodon_api_controller.ex
+++ b/lib/pleroma/web/mastodon_api/mastodon_api_controller.ex
@@ -8,6 +8,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do
alias Pleroma.Activity
alias Pleroma.Bookmark
alias Pleroma.Config
+ alias Pleroma.Conversation.Participation
alias Pleroma.Filter
alias Pleroma.Formatter
alias Pleroma.Notification
@@ -24,6 +25,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do
alias Pleroma.Web.CommonAPI
alias Pleroma.Web.MastodonAPI.AccountView
alias Pleroma.Web.MastodonAPI.AppView
+ alias Pleroma.Web.MastodonAPI.ConversationView
alias Pleroma.Web.MastodonAPI.FilterView
alias Pleroma.Web.MastodonAPI.ListView
alias Pleroma.Web.MastodonAPI.MastodonAPI
@@ -35,20 +37,31 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do
alias Pleroma.Web.MediaProxy
alias Pleroma.Web.OAuth.App
alias Pleroma.Web.OAuth.Authorization
+ alias Pleroma.Web.OAuth.Scopes
alias Pleroma.Web.OAuth.Token
+ alias Pleroma.Web.TwitterAPI.TwitterAPI
alias Pleroma.Web.ControllerHelper
import Ecto.Query
require Logger
+ plug(
+ Pleroma.Plugs.RateLimitPlug,
+ %{
+ max_requests: Config.get([:app_account_creation, :max_requests]),
+ interval: Config.get([:app_account_creation, :interval])
+ }
+ when action in [:account_register]
+ )
+
@httpoison Application.get_env(:pleroma, :httpoison)
@local_mastodon_name "Mastodon-Local"
action_fallback(:errors)
def create_app(conn, params) do
- scopes = ControllerHelper.oauth_scopes(params, ["read"])
+ scopes = Scopes.fetch_scopes(params, ["read"])
app_attrs =
params
@@ -165,7 +178,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do
end
end
- @mastodon_api_level "2.5.0"
+ @mastodon_api_level "2.7.2"
def masto_instance(conn, _params) do
instance = Config.get(:instance)
@@ -293,8 +306,6 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do
|> ActivityPub.contain_timeline(user)
|> Enum.reverse()
- user = Repo.preload(user, bookmarks: :activity)
-
conn
|> add_link_headers(:home_timeline, activities)
|> put_view(StatusView)
@@ -313,8 +324,6 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do
|> ActivityPub.fetch_public_activities()
|> Enum.reverse()
- user = Repo.preload(user, bookmarks: :activity)
-
conn
|> add_link_headers(:public_timeline, activities, false, %{"local" => local_only})
|> put_view(StatusView)
@@ -322,8 +331,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do
end
def user_statuses(%{assigns: %{user: reading_user}} = conn, params) do
- with %User{} = user <- User.get_cached_by_id(params["id"]),
- reading_user <- Repo.preload(reading_user, :bookmarks) do
+ with %User{} = user <- User.get_cached_by_id(params["id"]) do
activities = ActivityPub.fetch_user_activities(user, reading_user, params)
conn
@@ -350,8 +358,6 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do
|> ActivityPub.fetch_activities_query(params)
|> Pagination.fetch_paginated(params)
- user = Repo.preload(user, bookmarks: :activity)
-
conn
|> add_link_headers(:dm_timeline, activities)
|> put_view(StatusView)
@@ -361,8 +367,6 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do
def get_status(%{assigns: %{user: user}} = conn, %{"id" => id}) do
with %Activity{} = activity <- Activity.get_by_id_with_object(id),
true <- Visibility.visible_for_user?(activity, user) do
- user = Repo.preload(user, bookmarks: :activity)
-
conn
|> put_view(StatusView)
|> try_render("status.json", %{activity: activity, for: user})
@@ -512,8 +516,6 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do
def reblog_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
with {:ok, announce, _activity} <- CommonAPI.repeat(ap_id_or_id, user),
%Activity{} = announce <- Activity.normalize(announce.data) do
- user = Repo.preload(user, bookmarks: :activity)
-
conn
|> put_view(StatusView)
|> try_render("status.json", %{activity: announce, for: user, as: :activity})
@@ -523,8 +525,6 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do
def unreblog_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
with {:ok, _unannounce, %{data: %{"id" => id}}} <- CommonAPI.unrepeat(ap_id_or_id, user),
%Activity{} = activity <- Activity.get_create_by_object_ap_id_with_object(id) do
- user = Repo.preload(user, bookmarks: :activity)
-
conn
|> put_view(StatusView)
|> try_render("status.json", %{activity: activity, for: user, as: :activity})
@@ -575,8 +575,6 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do
%User{} = user <- User.get_cached_by_nickname(user.nickname),
true <- Visibility.visible_for_user?(activity, user),
{:ok, _bookmark} <- Bookmark.create(user.id, activity.id) do
- user = Repo.preload(user, bookmarks: :activity)
-
conn
|> put_view(StatusView)
|> try_render("status.json", %{activity: activity, for: user, as: :activity})
@@ -588,8 +586,6 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do
%User{} = user <- User.get_cached_by_nickname(user.nickname),
true <- Visibility.visible_for_user?(activity, user),
{:ok, _bookmark} <- Bookmark.destroy(user.id, activity.id) do
- user = Repo.preload(user, bookmarks: :activity)
-
conn
|> put_view(StatusView)
|> try_render("status.json", %{activity: activity, for: user, as: :activity})
@@ -1110,8 +1106,6 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do
ActivityPub.fetch_activities([], params)
|> Enum.reverse()
- user = Repo.preload(user, bookmarks: :activity)
-
conn
|> add_link_headers(:favourites, activities)
|> put_view(StatusView)
@@ -1157,7 +1151,6 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do
def bookmarks(%{assigns: %{user: user}} = conn, params) do
user = User.get_cached_by_id(user.id)
- user = Repo.preload(user, bookmarks: :activity)
bookmarks =
Bookmark.for_user_query(user.id)
@@ -1165,7 +1158,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do
activities =
bookmarks
- |> Enum.map(fn b -> b.activity end)
+ |> Enum.map(fn b -> Map.put(b.activity, :bookmark, Map.delete(b, :activity)) end)
conn
|> add_link_headers(:bookmarks, bookmarks)
@@ -1274,8 +1267,6 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do
|> ActivityPub.fetch_activities_bounded(following, params)
|> Enum.reverse()
- user = Repo.preload(user, bookmarks: :activity)
-
conn
|> put_view(StatusView)
|> render("index.json", %{activities: activities, for: user, as: :activity})
@@ -1555,7 +1546,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do
user_id: user.id,
phrase: phrase,
context: context,
- hide: Map.get(params, "irreversible", nil),
+ hide: Map.get(params, "irreversible", false),
whole_word: Map.get(params, "boolean", true)
# expires_at
}
@@ -1712,6 +1703,78 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do
end
end
+ def account_register(
+ %{assigns: %{app: app}} = conn,
+ %{"username" => nickname, "email" => _, "password" => _, "agreement" => true} = params
+ ) do
+ params =
+ params
+ |> Map.take([
+ "email",
+ "captcha_solution",
+ "captcha_token",
+ "captcha_answer_data",
+ "token",
+ "password"
+ ])
+ |> Map.put("nickname", nickname)
+ |> Map.put("fullname", params["fullname"] || nickname)
+ |> Map.put("bio", params["bio"] || "")
+ |> Map.put("confirm", params["password"])
+
+ with {:ok, user} <- TwitterAPI.register_user(params, need_confirmation: true),
+ {:ok, token} <- Token.create_token(app, user, %{scopes: app.scopes}) do
+ json(conn, %{
+ token_type: "Bearer",
+ access_token: token.token,
+ scope: app.scopes,
+ created_at: Token.Utils.format_created_at(token)
+ })
+ else
+ {:error, errors} ->
+ conn
+ |> put_status(400)
+ |> json(Jason.encode!(errors))
+ end
+ end
+
+ def account_register(%{assigns: %{app: _app}} = conn, _params) do
+ conn
+ |> put_status(400)
+ |> json(%{error: "Missing parameters"})
+ end
+
+ def account_register(conn, _) do
+ conn
+ |> put_status(403)
+ |> json(%{error: "Invalid credentials"})
+ end
+
+ def conversations(%{assigns: %{user: user}} = conn, params) do
+ participations = Participation.for_user_with_last_activity_id(user, params)
+
+ conversations =
+ Enum.map(participations, fn participation ->
+ ConversationView.render("participation.json", %{participation: participation, user: user})
+ end)
+
+ conn
+ |> add_link_headers(:conversations, participations)
+ |> json(conversations)
+ end
+
+ def conversation_read(%{assigns: %{user: user}} = conn, %{"id" => participation_id}) do
+ with %Participation{} = participation <-
+ Repo.get_by(Participation, id: participation_id, user_id: user.id),
+ {:ok, participation} <- Participation.mark_as_read(participation) do
+ participation_view =
+ ConversationView.render("participation.json", %{participation: participation, user: user})
+
+ conn
+ |> json(participation_view)
+ end
+ end
+
def try_render(conn, target, params)
when is_binary(target) do
res = render(conn, target, params)
diff --git a/lib/pleroma/web/mastodon_api/views/conversation_view.ex b/lib/pleroma/web/mastodon_api/views/conversation_view.ex
new file mode 100644
index 000000000..8e8f7cf31
--- /dev/null
+++ b/lib/pleroma/web/mastodon_api/views/conversation_view.ex
@@ -0,0 +1,38 @@
+defmodule Pleroma.Web.MastodonAPI.ConversationView do
+ use Pleroma.Web, :view
+
+ alias Pleroma.Activity
+ alias Pleroma.Repo
+ alias Pleroma.Web.ActivityPub.ActivityPub
+ alias Pleroma.Web.MastodonAPI.AccountView
+ alias Pleroma.Web.MastodonAPI.StatusView
+
+ def render("participation.json", %{participation: participation, user: user}) do
+ participation = Repo.preload(participation, conversation: :users)
+
+ last_activity_id =
+ with nil <- participation.last_activity_id do
+ ActivityPub.fetch_latest_activity_id_for_context(participation.conversation.ap_id, %{
+ "user" => user,
+ "blocking_user" => user
+ })
+ end
+
+ activity = Activity.get_by_id_with_object(last_activity_id)
+
+ last_status = StatusView.render("status.json", %{activity: activity, for: user})
+
+ accounts =
+ AccountView.render("accounts.json", %{
+ users: participation.conversation.users,
+ as: :user
+ })
+
+ %{
+ id: participation.id |> to_string(),
+ accounts: accounts,
+ unread: !participation.read,
+ last_status: last_status
+ }
+ end
+end
diff --git a/lib/pleroma/web/mastodon_api/views/status_view.ex b/lib/pleroma/web/mastodon_api/views/status_view.ex
index 62d064d71..bd2372944 100644
--- a/lib/pleroma/web/mastodon_api/views/status_view.ex
+++ b/lib/pleroma/web/mastodon_api/views/status_view.ex
@@ -75,18 +75,22 @@ defmodule Pleroma.Web.MastodonAPI.StatusView do
def render(
"status.json",
- %{activity: %{data: %{"type" => "Announce", "object" => object}} = activity} = opts
+ %{activity: %{data: %{"type" => "Announce", "object" => _object}} = activity} = opts
) do
user = get_user(activity.data["actor"])
created_at = Utils.to_masto_date(activity.data["published"])
+ activity_object = Object.normalize(activity)
+
+ reblogged_activity =
+ Activity.create_by_object_ap_id(activity_object.data["id"])
+ |> Activity.with_preloaded_bookmark(opts[:for])
+ |> Repo.one()
- reblogged_activity = Activity.get_create_by_object_ap_id(object)
reblogged = render("status.json", Map.put(opts, :activity, reblogged_activity))
- activity_object = Object.normalize(activity)
favorited = opts[:for] && opts[:for].ap_id in (activity_object.data["likes"] || [])
- bookmarked = opts[:for] && CommonAPI.bookmarked?(opts[:for], reblogged_activity)
+ bookmarked = Activity.get_bookmark(reblogged_activity, opts[:for]) != nil
mentions =
activity.recipients
@@ -96,8 +100,8 @@ defmodule Pleroma.Web.MastodonAPI.StatusView do
%{
id: to_string(activity.id),
- uri: object,
- url: object,
+ uri: activity_object.data["id"],
+ url: activity_object.data["id"],
account: AccountView.render("account.json", %{user: user}),
in_reply_to_id: nil,
in_reply_to_account_id: nil,
@@ -149,7 +153,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusView do
favorited = opts[:for] && opts[:for].ap_id in (object.data["likes"] || [])
- bookmarked = opts[:for] && CommonAPI.bookmarked?(opts[:for], activity)
+ bookmarked = Activity.get_bookmark(activity, opts[:for]) != nil
attachment_data = object.data["attachment"] || []
attachments = render_many(attachment_data, StatusView, "attachment.json", as: :attachment)
diff --git a/lib/pleroma/web/nodeinfo/nodeinfo_controller.ex b/lib/pleroma/web/nodeinfo/nodeinfo_controller.ex
index 216a962bd..3bf2a0fbc 100644
--- a/lib/pleroma/web/nodeinfo/nodeinfo_controller.ex
+++ b/lib/pleroma/web/nodeinfo/nodeinfo_controller.ex
@@ -10,6 +10,7 @@ defmodule Pleroma.Web.Nodeinfo.NodeinfoController do
alias Pleroma.User
alias Pleroma.Web
alias Pleroma.Web.ActivityPub.MRF
+ alias Pleroma.Web.Federator.Publisher
plug(Pleroma.Web.FederatingPlug)
@@ -137,7 +138,7 @@ defmodule Pleroma.Web.Nodeinfo.NodeinfoController do
name: Pleroma.Application.name() |> String.downcase(),
version: Pleroma.Application.version()
},
- protocols: ["ostatus", "activitypub"],
+ protocols: Publisher.gather_nodeinfo_protocol_names(),
services: %{
inbound: [],
outbound: []
diff --git a/lib/pleroma/web/oauth.ex b/lib/pleroma/web/oauth.ex
index d2835a0ba..280cf28c0 100644
--- a/lib/pleroma/web/oauth.ex
+++ b/lib/pleroma/web/oauth.ex
@@ -3,18 +3,4 @@
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.OAuth do
- def parse_scopes(scopes, _default) when is_list(scopes) do
- Enum.filter(scopes, &(&1 not in [nil, ""]))
- end
-
- def parse_scopes(scopes, default) when is_binary(scopes) do
- scopes
- |> String.trim()
- |> String.split(~r/[\s,]+/)
- |> parse_scopes(default)
- end
-
- def parse_scopes(_, default) do
- default
- end
end
diff --git a/lib/pleroma/web/oauth/app.ex b/lib/pleroma/web/oauth/app.ex
index bccc2ac96..ddcdb1871 100644
--- a/lib/pleroma/web/oauth/app.ex
+++ b/lib/pleroma/web/oauth/app.ex
@@ -7,6 +7,7 @@ defmodule Pleroma.Web.OAuth.App do
import Ecto.Changeset
@type t :: %__MODULE__{}
+
schema "apps" do
field(:client_name, :string)
field(:redirect_uris, :string)
diff --git a/lib/pleroma/web/oauth/authorization.ex b/lib/pleroma/web/oauth/authorization.ex
index ca3901cc4..b47688de1 100644
--- a/lib/pleroma/web/oauth/authorization.ex
+++ b/lib/pleroma/web/oauth/authorization.ex
@@ -14,6 +14,7 @@ defmodule Pleroma.Web.OAuth.Authorization do
import Ecto.Query
@type t :: %__MODULE__{}
+
schema "oauth_authorizations" do
field(:token, :string)
field(:scopes, {:array, :string}, default: [])
@@ -25,28 +26,45 @@ defmodule Pleroma.Web.OAuth.Authorization do
timestamps()
end
+ @spec create_authorization(App.t(), User.t() | %{}, [String.t()] | nil) ::
+ {:ok, Authorization.t()} | {:error, Changeset.t()}
def create_authorization(%App{} = app, %User{} = user, scopes \\ nil) do
- scopes = scopes || app.scopes
- token = :crypto.strong_rand_bytes(32) |> Base.url_encode64(padding: false)
-
- authorization = %Authorization{
- token: token,
- used: false,
+ %{
+ scopes: scopes || app.scopes,
user_id: user.id,
- app_id: app.id,
- scopes: scopes,
- valid_until: NaiveDateTime.add(NaiveDateTime.utc_now(), 60 * 10)
+ app_id: app.id
}
+ |> create_changeset()
+ |> Repo.insert()
+ end
+
+ @spec create_changeset(map()) :: Changeset.t()
+ def create_changeset(attrs \\ %{}) do
+ %Authorization{}
+ |> cast(attrs, [:user_id, :app_id, :scopes, :valid_until])
+ |> validate_required([:app_id, :scopes])
+ |> add_token()
+ |> add_lifetime()
+ end
+
+ defp add_token(changeset) do
+ token = :crypto.strong_rand_bytes(32) |> Base.url_encode64(padding: false)
+ put_change(changeset, :token, token)
+ end
- Repo.insert(authorization)
+ defp add_lifetime(changeset) do
+ put_change(changeset, :valid_until, NaiveDateTime.add(NaiveDateTime.utc_now(), 60 * 10))
end
+ @spec use_changeset(Authtorizatiton.t(), map()) :: Changeset.t()
def use_changeset(%Authorization{} = auth, params) do
auth
|> cast(params, [:used])
|> validate_required([:used])
end
+ @spec use_token(Authorization.t()) ::
+ {:ok, Authorization.t()} | {:error, Changeset.t()} | {:error, String.t()}
def use_token(%Authorization{used: false, valid_until: valid_until} = auth) do
if NaiveDateTime.diff(NaiveDateTime.utc_now(), valid_until) < 0 do
Repo.update(use_changeset(auth, %{used: true}))
@@ -57,6 +75,7 @@ defmodule Pleroma.Web.OAuth.Authorization do
def use_token(%Authorization{used: true}), do: {:error, "already used"}
+ @spec delete_user_authorizations(User.t()) :: {integer(), any()}
def delete_user_authorizations(%User{id: user_id}) do
from(
a in Pleroma.Web.OAuth.Authorization,
diff --git a/lib/pleroma/web/oauth/oauth_controller.ex b/lib/pleroma/web/oauth/oauth_controller.ex
index e3c01217d..4ee8339e2 100644
--- a/lib/pleroma/web/oauth/oauth_controller.ex
+++ b/lib/pleroma/web/oauth/oauth_controller.ex
@@ -15,8 +15,7 @@ defmodule Pleroma.Web.OAuth.OAuthController do
alias Pleroma.Web.OAuth.Token
alias Pleroma.Web.OAuth.Token.Strategy.RefreshToken
alias Pleroma.Web.OAuth.Token.Strategy.Revoke, as: RevokeToken
-
- import Pleroma.Web.ControllerHelper, only: [oauth_scopes: 2]
+ alias Pleroma.Web.OAuth.Scopes
if Pleroma.Config.oauth_consumer_enabled?(), do: plug(Ueberauth)
@@ -57,7 +56,7 @@ defmodule Pleroma.Web.OAuth.OAuthController do
defp do_authorize(conn, params) do
app = Repo.get_by(App, client_id: params["client_id"])
available_scopes = (app && app.scopes) || []
- scopes = oauth_scopes(params, nil) || available_scopes
+ scopes = Scopes.fetch_scopes(params, available_scopes)
# Note: `params` might differ from `conn.params`; use `@params` not `@conn.params` in template
render(conn, Authenticator.auth_template(), %{
@@ -113,7 +112,7 @@ defmodule Pleroma.Web.OAuth.OAuthController do
defp handle_create_authorization_error(
conn,
- {scopes_issue, _},
+ {:error, scopes_issue},
%{"authorization" => _} = params
)
when scopes_issue in [:unsupported_scopes, :missing_scopes] do
@@ -184,9 +183,7 @@ defmodule Pleroma.Web.OAuth.OAuthController do
%App{} = app <- get_app_from_request(conn, params),
{:auth_active, true} <- {:auth_active, User.auth_active?(user)},
{:user_active, true} <- {:user_active, !user.info.deactivated},
- scopes <- oauth_scopes(params, app.scopes),
- [] <- scopes -- app.scopes,
- true <- Enum.any?(scopes),
+ {:ok, scopes} <- validate_scopes(app, params),
{:ok, auth} <- Authorization.create_authorization(app, user, scopes),
{:ok, token} <- Token.exchange_token(app, auth) do
json(conn, response_token(user, token))
@@ -221,6 +218,28 @@ defmodule Pleroma.Web.OAuth.OAuthController do
token_exchange(conn, params)
end
+ def token_exchange(conn, %{"grant_type" => "client_credentials"} = params) do
+ with %App{} = app <- get_app_from_request(conn, params),
+ {:ok, auth} <- Authorization.create_authorization(app, %User{}),
+ {:ok, token} <- Token.exchange_token(app, auth),
+ {:ok, inserted_at} <- DateTime.from_naive(token.inserted_at, "Etc/UTC") do
+ response = %{
+ token_type: "Bearer",
+ access_token: token.token,
+ refresh_token: token.refresh_token,
+ created_at: DateTime.to_unix(inserted_at),
+ expires_in: 60 * 10,
+ scope: Enum.join(token.scopes, " ")
+ }
+
+ json(conn, response)
+ else
+ _error ->
+ put_status(conn, 400)
+ |> json(%{error: "Invalid credentials"})
+ end
+ end
+
# Bad request
def token_exchange(conn, params), do: bad_request(conn, params)
@@ -247,14 +266,15 @@ defmodule Pleroma.Web.OAuth.OAuthController do
@doc "Prepares OAuth request to provider for Ueberauth"
def prepare_request(conn, %{"provider" => provider, "authorization" => auth_attrs}) do
scope =
- oauth_scopes(auth_attrs, [])
- |> Enum.join(" ")
+ auth_attrs
+ |> Scopes.fetch_scopes([])
+ |> Scopes.to_string()
state =
auth_attrs
|> Map.delete("scopes")
|> Map.put("scope", scope)
- |> Poison.encode!()
+ |> Jason.encode!()
params =
auth_attrs
@@ -318,7 +338,7 @@ defmodule Pleroma.Web.OAuth.OAuthController do
end
defp callback_params(%{"state" => state} = params) do
- Map.merge(params, Poison.decode!(state))
+ Map.merge(params, Jason.decode!(state))
end
def registration_details(conn, %{"authorization" => auth_attrs}) do
@@ -326,7 +346,7 @@ defmodule Pleroma.Web.OAuth.OAuthController do
client_id: auth_attrs["client_id"],
redirect_uri: auth_attrs["redirect_uri"],
state: auth_attrs["state"],
- scopes: oauth_scopes(auth_attrs, []),
+ scopes: Scopes.fetch_scopes(auth_attrs, []),
nickname: auth_attrs["nickname"],
email: auth_attrs["email"]
})
@@ -401,10 +421,7 @@ defmodule Pleroma.Web.OAuth.OAuthController do
{:get_user, (user && {:ok, user}) || Authenticator.get_user(conn)},
%App{} = app <- Repo.get_by(App, client_id: client_id),
true <- redirect_uri in String.split(app.redirect_uris),
- scopes <- oauth_scopes(auth_attrs, []),
- {:unsupported_scopes, []} <- {:unsupported_scopes, scopes -- app.scopes},
- # Note: `scope` param is intentionally not optional in this context
- {:missing_scopes, false} <- {:missing_scopes, scopes == []},
+ {:ok, scopes} <- validate_scopes(app, auth_attrs),
{:auth_active, true} <- {:auth_active, User.auth_active?(user)} do
Authorization.create_authorization(app, user, scopes)
end
@@ -458,4 +475,12 @@ defmodule Pleroma.Web.OAuth.OAuthController do
}
|> Map.merge(opts)
end
+
+ @spec validate_scopes(App.t(), map()) ::
+ {:ok, list()} | {:error, :missing_scopes | :unsupported_scopes}
+ defp validate_scopes(app, params) do
+ params
+ |> Scopes.fetch_scopes(app.scopes)
+ |> Scopes.validates(app.scopes)
+ end
end
diff --git a/lib/pleroma/web/oauth/scopes.ex b/lib/pleroma/web/oauth/scopes.ex
new file mode 100644
index 000000000..ad9dfb260
--- /dev/null
+++ b/lib/pleroma/web/oauth/scopes.ex
@@ -0,0 +1,67 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.Web.OAuth.Scopes do
+ @moduledoc """
+ Functions for dealing with scopes.
+ """
+
+ @doc """
+ Fetch scopes from requiest params.
+
+ Note: `scopes` is used by Mastodon — supporting it but sticking to
+ OAuth's standard `scope` wherever we control it
+ """
+ @spec fetch_scopes(map(), list()) :: list()
+ def fetch_scopes(params, default) do
+ parse_scopes(params["scope"] || params["scopes"], default)
+ end
+
+ def parse_scopes(scopes, _default) when is_list(scopes) do
+ Enum.filter(scopes, &(&1 not in [nil, ""]))
+ end
+
+ def parse_scopes(scopes, default) when is_binary(scopes) do
+ scopes
+ |> to_list
+ |> parse_scopes(default)
+ end
+
+ def parse_scopes(_, default) do
+ default
+ end
+
+ @doc """
+ Convert scopes string to list
+ """
+ @spec to_list(binary()) :: [binary()]
+ def to_list(nil), do: []
+
+ def to_list(str) do
+ str
+ |> String.trim()
+ |> String.split(~r/[\s,]+/)
+ end
+
+ @doc """
+ Convert scopes list to string
+ """
+ @spec to_string(list()) :: binary()
+ def to_string(scopes), do: Enum.join(scopes, " ")
+
+ @doc """
+ Validates scopes.
+ """
+ @spec validates(list() | nil, list()) ::
+ {:ok, list()} | {:error, :missing_scopes | :unsupported_scopes}
+ def validates([], _app_scopes), do: {:error, :missing_scopes}
+ def validates(nil, _app_scopes), do: {:error, :missing_scopes}
+
+ def validates(scopes, app_scopes) do
+ case scopes -- app_scopes do
+ [] -> {:ok, scopes}
+ _ -> {:error, :unsupported_scopes}
+ end
+ end
+end
diff --git a/lib/pleroma/web/oauth/token.ex b/lib/pleroma/web/oauth/token.ex
index 4e5d1d118..ef047d565 100644
--- a/lib/pleroma/web/oauth/token.ex
+++ b/lib/pleroma/web/oauth/token.ex
@@ -45,12 +45,16 @@ defmodule Pleroma.Web.OAuth.Token do
|> Repo.find_resource()
end
+ @spec exchange_token(App.t(), Authorization.t()) ::
+ {:ok, Token.t()} | {:error, Changeset.t()}
def exchange_token(app, auth) do
with {:ok, auth} <- Authorization.use_token(auth),
true <- auth.app_id == app.id do
+ user = if auth.user_id, do: User.get_cached_by_id(auth.user_id), else: %User{}
+
create_token(
app,
- User.get_cached_by_id(auth.user_id),
+ user,
%{scopes: auth.scopes}
)
end
@@ -81,12 +85,13 @@ defmodule Pleroma.Web.OAuth.Token do
|> validate_required([:valid_until])
end
+ @spec create_token(App.t(), User.t(), map()) :: {:ok, Token} | {:error, Changeset.t()}
def create_token(%App{} = app, %User{} = user, attrs \\ %{}) do
%__MODULE__{user_id: user.id, app_id: app.id}
|> cast(%{scopes: attrs[:scopes] || app.scopes}, [:scopes])
- |> validate_required([:scopes, :user_id, :app_id])
+ |> validate_required([:scopes, :app_id])
|> put_valid_until(attrs)
- |> put_token
+ |> put_token()
|> put_refresh_token(attrs)
|> Repo.insert()
end
diff --git a/lib/pleroma/web/ostatus/activity_representer.ex b/lib/pleroma/web/ostatus/activity_representer.ex
index 166691a09..95037125d 100644
--- a/lib/pleroma/web/ostatus/activity_representer.ex
+++ b/lib/pleroma/web/ostatus/activity_representer.ex
@@ -18,15 +18,18 @@ defmodule Pleroma.Web.OStatus.ActivityRepresenter do
end
end
- defp get_in_reply_to(%{"object" => %{"inReplyTo" => in_reply_to}}) do
- [
- {:"thr:in-reply-to",
- [ref: to_charlist(in_reply_to), href: to_charlist(get_href(in_reply_to))], []}
- ]
+ defp get_in_reply_to(activity) do
+ with %Object{data: %{"inReplyTo" => in_reply_to}} <- Object.normalize(activity) do
+ [
+ {:"thr:in-reply-to",
+ [ref: to_charlist(in_reply_to), href: to_charlist(get_href(in_reply_to))], []}
+ ]
+ else
+ _ ->
+ []
+ end
end
- defp get_in_reply_to(_), do: []
-
defp get_mentions(to) do
Enum.map(to, fn id ->
cond do
@@ -98,7 +101,7 @@ defmodule Pleroma.Web.OStatus.ActivityRepresenter do
[]}
end)
- in_reply_to = get_in_reply_to(activity.data)
+ in_reply_to = get_in_reply_to(activity)
author = if with_author, do: [{:author, UserRepresenter.to_simple_form(user)}], else: []
mentions = activity.recipients |> get_mentions
@@ -146,7 +149,6 @@ defmodule Pleroma.Web.OStatus.ActivityRepresenter do
updated_at = activity.data["published"]
inserted_at = activity.data["published"]
- _in_reply_to = get_in_reply_to(activity.data)
author = if with_author, do: [{:author, UserRepresenter.to_simple_form(user)}], else: []
mentions = activity.recipients |> get_mentions
@@ -177,7 +179,6 @@ defmodule Pleroma.Web.OStatus.ActivityRepresenter do
updated_at = activity.data["published"]
inserted_at = activity.data["published"]
- _in_reply_to = get_in_reply_to(activity.data)
author = if with_author, do: [{:author, UserRepresenter.to_simple_form(user)}], else: []
retweeted_activity = Activity.get_create_by_object_ap_id(activity.data["object"])
diff --git a/lib/pleroma/web/ostatus/ostatus.ex b/lib/pleroma/web/ostatus/ostatus.ex
index 4744c6d83..61515b31e 100644
--- a/lib/pleroma/web/ostatus/ostatus.ex
+++ b/lib/pleroma/web/ostatus/ostatus.ex
@@ -16,6 +16,7 @@ defmodule Pleroma.Web.OStatus do
alias Pleroma.Web
alias Pleroma.Web.ActivityPub.ActivityPub
alias Pleroma.Web.ActivityPub.Transmogrifier
+ alias Pleroma.Web.ActivityPub.Visibility
alias Pleroma.Web.OStatus.DeleteHandler
alias Pleroma.Web.OStatus.FollowHandler
alias Pleroma.Web.OStatus.NoteHandler
@@ -30,7 +31,7 @@ defmodule Pleroma.Web.OStatus do
is_nil(object) ->
false
- object.data["type"] == "Note" ->
+ Visibility.is_public?(activity) && object.data["type"] == "Note" ->
true
true ->
diff --git a/lib/pleroma/web/router.ex b/lib/pleroma/web/router.ex
index 5f7617ece..80af0afe1 100644
--- a/lib/pleroma/web/router.ex
+++ b/lib/pleroma/web/router.ex
@@ -146,34 +146,52 @@ defmodule Pleroma.Web.Router do
scope "/api/pleroma/admin", Pleroma.Web.AdminAPI do
pipe_through([:admin_api, :oauth_write])
- post("/user/follow", AdminAPIController, :user_follow)
- post("/user/unfollow", AdminAPIController, :user_unfollow)
-
- get("/users", AdminAPIController, :list_users)
- get("/users/:nickname", AdminAPIController, :user_show)
+ post("/users/follow", AdminAPIController, :user_follow)
+ post("/users/unfollow", AdminAPIController, :user_unfollow)
+ # TODO: to be removed at version 1.0
delete("/user", AdminAPIController, :user_delete)
- patch("/users/:nickname/toggle_activation", AdminAPIController, :user_toggle_activation)
post("/user", AdminAPIController, :user_create)
+
+ delete("/users", AdminAPIController, :user_delete)
+ post("/users", AdminAPIController, :user_create)
+ patch("/users/:nickname/toggle_activation", AdminAPIController, :user_toggle_activation)
put("/users/tag", AdminAPIController, :tag_users)
delete("/users/tag", AdminAPIController, :untag_users)
+ # TODO: to be removed at version 1.0
get("/permission_group/:nickname", AdminAPIController, :right_get)
get("/permission_group/:nickname/:permission_group", AdminAPIController, :right_get)
post("/permission_group/:nickname/:permission_group", AdminAPIController, :right_add)
delete("/permission_group/:nickname/:permission_group", AdminAPIController, :right_delete)
- put("/activation_status/:nickname", AdminAPIController, :set_activation_status)
+ get("/users/:nickname/permission_group", AdminAPIController, :right_get)
+ get("/users/:nickname/permission_group/:permission_group", AdminAPIController, :right_get)
+ post("/users/:nickname/permission_group/:permission_group", AdminAPIController, :right_add)
+
+ delete(
+ "/users/:nickname/permission_group/:permission_group",
+ AdminAPIController,
+ :right_delete
+ )
+
+ put("/users/:nickname/activation_status", AdminAPIController, :set_activation_status)
post("/relay", AdminAPIController, :relay_follow)
delete("/relay", AdminAPIController, :relay_unfollow)
- get("/invite_token", AdminAPIController, :get_invite_token)
- get("/invites", AdminAPIController, :invites)
- post("/revoke_invite", AdminAPIController, :revoke_invite)
- post("/email_invite", AdminAPIController, :email_invite)
+ get("/users/invite_token", AdminAPIController, :get_invite_token)
+ get("/users/invites", AdminAPIController, :invites)
+ post("/users/revoke_invite", AdminAPIController, :revoke_invite)
+ post("/users/email_invite", AdminAPIController, :email_invite)
+ # TODO: to be removed at version 1.0
get("/password_reset", AdminAPIController, :get_password_reset)
+
+ get("/users/:nickname/password_reset", AdminAPIController, :get_password_reset)
+
+ get("/users", AdminAPIController, :list_users)
+ get("/users/:nickname", AdminAPIController, :user_show)
end
scope "/", Pleroma.Web.TwitterAPI do
@@ -277,6 +295,9 @@ defmodule Pleroma.Web.Router do
get("/suggestions", MastodonAPIController, :suggestions)
+ get("/conversations", MastodonAPIController, :conversations)
+ post("/conversations/:id/read", MastodonAPIController, :conversation_read)
+
get("/endorsements", MastodonAPIController, :empty_array)
get("/pleroma/flavour", MastodonAPIController, :get_flavour)
@@ -365,6 +386,8 @@ defmodule Pleroma.Web.Router do
scope "/api/v1", Pleroma.Web.MastodonAPI do
pipe_through(:api)
+ post("/accounts", MastodonAPIController, :account_register)
+
get("/instance", MastodonAPIController, :masto_instance)
get("/instance/peers", MastodonAPIController, :peers)
post("/apps", MastodonAPIController, :create_app)
diff --git a/lib/pleroma/web/salmon/salmon.ex b/lib/pleroma/web/salmon/salmon.ex
index 0a9e51656..42709ab47 100644
--- a/lib/pleroma/web/salmon/salmon.ex
+++ b/lib/pleroma/web/salmon/salmon.ex
@@ -3,12 +3,18 @@
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.Salmon do
+ @behaviour Pleroma.Web.Federator.Publisher
+
@httpoison Application.get_env(:pleroma, :httpoison)
use Bitwise
+ alias Pleroma.Activity
alias Pleroma.Instances
alias Pleroma.User
+ alias Pleroma.Web.ActivityPub.Visibility
+ alias Pleroma.Web.Federator.Publisher
+ alias Pleroma.Web.OStatus
alias Pleroma.Web.OStatus.ActivityRepresenter
alias Pleroma.Web.XML
@@ -165,12 +171,12 @@ defmodule Pleroma.Web.Salmon do
end
@doc "Pushes an activity to remote account."
- def send_to_user(%{recipient: %{info: %{salmon: salmon}}} = params),
- do: send_to_user(Map.put(params, :recipient, salmon))
+ def publish_one(%{recipient: %{info: %{salmon: salmon}}} = params),
+ do: publish_one(Map.put(params, :recipient, salmon))
- def send_to_user(%{recipient: url, feed: feed, poster: poster} = params) when is_binary(url) do
+ def publish_one(%{recipient: url, feed: feed} = params) when is_binary(url) do
with {:ok, %{status: code}} when code in 200..299 <-
- poster.(
+ @httpoison.post(
url,
feed,
[{"Content-Type", "application/magic-envelope+xml"}]
@@ -184,11 +190,11 @@ defmodule Pleroma.Web.Salmon do
e ->
unless params[:unreachable_since], do: Instances.set_reachable(url)
Logger.debug(fn -> "Pushing Salmon to #{url} failed, #{inspect(e)}" end)
- :error
+ {:error, "Unreachable instance"}
end
end
- def send_to_user(_), do: :noop
+ def publish_one(_), do: :noop
@supported_activities [
"Create",
@@ -199,13 +205,19 @@ defmodule Pleroma.Web.Salmon do
"Delete"
]
+ def is_representable?(%Activity{data: %{"type" => type}} = activity)
+ when type in @supported_activities,
+ do: Visibility.is_public?(activity)
+
+ def is_representable?(_), do: false
+
@doc """
Publishes an activity to remote accounts
"""
- @spec publish(User.t(), Pleroma.Activity.t(), Pleroma.HTTP.t()) :: none
- def publish(user, activity, poster \\ &@httpoison.post/3)
+ @spec publish(User.t(), Pleroma.Activity.t()) :: none
+ def publish(user, activity)
- def publish(%{info: %{keys: keys}} = user, %{data: %{"type" => type}} = activity, poster)
+ def publish(%{info: %{keys: keys}} = user, %{data: %{"type" => type}} = activity)
when type in @supported_activities do
feed = ActivityRepresenter.to_simple_form(activity, user, true)
@@ -229,15 +241,29 @@ defmodule Pleroma.Web.Salmon do
|> Enum.each(fn remote_user ->
Logger.debug(fn -> "Sending Salmon to #{remote_user.ap_id}" end)
- Pleroma.Web.Federator.publish_single_salmon(%{
+ Publisher.enqueue_one(__MODULE__, %{
recipient: remote_user,
feed: feed,
- poster: poster,
unreachable_since: reachable_urls_metadata[remote_user.info.salmon]
})
end)
end
end
- def publish(%{id: id}, _, _), do: Logger.debug(fn -> "Keys missing for user #{id}" end)
+ def publish(%{id: id}, _), do: Logger.debug(fn -> "Keys missing for user #{id}" end)
+
+ def gather_webfinger_links(%User{} = user) do
+ {:ok, _private, public} = keys_from_pem(user.info.keys)
+ magic_key = encode_key(public)
+
+ [
+ %{"rel" => "salmon", "href" => OStatus.salmon_path(user)},
+ %{
+ "rel" => "magic-public-key",
+ "href" => "data:application/magic-public-key,#{magic_key}"
+ }
+ ]
+ end
+
+ def gather_nodeinfo_protocol_names, do: []
end
diff --git a/lib/pleroma/web/streamer.ex b/lib/pleroma/web/streamer.ex
index 72eaf2084..133decfc4 100644
--- a/lib/pleroma/web/streamer.ex
+++ b/lib/pleroma/web/streamer.ex
@@ -6,6 +6,7 @@ defmodule Pleroma.Web.Streamer do
use GenServer
require Logger
alias Pleroma.Activity
+ alias Pleroma.Conversation.Participation
alias Pleroma.Notification
alias Pleroma.Object
alias Pleroma.User
@@ -71,6 +72,15 @@ defmodule Pleroma.Web.Streamer do
{:noreply, topics}
end
+ def handle_cast(%{action: :stream, topic: "participation", item: participation}, topics) do
+ user_topic = "direct:#{participation.user_id}"
+ Logger.debug("Trying to push a conversation participation to #{user_topic}\n\n")
+
+ push_to_socket(topics, user_topic, participation)
+
+ {:noreply, topics}
+ end
+
def handle_cast(%{action: :stream, topic: "list", item: item}, topics) do
# filter the recipient list if the activity is not public, see #270.
recipient_lists =
@@ -192,6 +202,19 @@ defmodule Pleroma.Web.Streamer do
|> Jason.encode!()
end
+ def represent_conversation(%Participation{} = participation) do
+ %{
+ event: "conversation",
+ payload:
+ Pleroma.Web.MastodonAPI.ConversationView.render("participation.json", %{
+ participation: participation,
+ user: participation.user
+ })
+ |> Jason.encode!()
+ }
+ |> Jason.encode!()
+ end
+
def push_to_socket(topics, topic, %Activity{data: %{"type" => "Announce"}} = item) do
Enum.each(topics[topic] || [], fn socket ->
# Get the current user so we have up-to-date blocks etc.
@@ -214,6 +237,12 @@ defmodule Pleroma.Web.Streamer do
end)
end
+ def push_to_socket(topics, topic, %Participation{} = participation) do
+ Enum.each(topics[topic] || [], fn socket ->
+ send(socket.transport_pid, {:text, represent_conversation(participation)})
+ end)
+ end
+
def push_to_socket(topics, topic, %Activity{
data: %{"type" => "Delete", "deleted_activity_id" => deleted_activity_id}
}) do
diff --git a/lib/pleroma/web/twitter_api/twitter_api.ex b/lib/pleroma/web/twitter_api/twitter_api.ex
index 1e48b0b39..41e1c2877 100644
--- a/lib/pleroma/web/twitter_api/twitter_api.ex
+++ b/lib/pleroma/web/twitter_api/twitter_api.ex
@@ -128,7 +128,7 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPI do
end
end
- def register_user(params) do
+ def register_user(params, opts \\ []) do
token = params["token"]
params = %{
@@ -162,13 +162,22 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPI do
# I have no idea how this error handling works
{:error, %{error: Jason.encode!(%{captcha: [error]})}}
else
- registrations_open = Pleroma.Config.get([:instance, :registrations_open])
- registration_process(registrations_open, params, token)
+ registration_process(
+ params,
+ %{
+ registrations_open: Pleroma.Config.get([:instance, :registrations_open]),
+ token: token
+ },
+ opts
+ )
end
end
- defp registration_process(registration_open, params, token)
- when registration_open == false or is_nil(registration_open) do
+ defp registration_process(params, %{registrations_open: true}, opts) do
+ create_user(params, opts)
+ end
+
+ defp registration_process(params, %{token: token}, opts) do
invite =
unless is_nil(token) do
Repo.get_by(UserInviteToken, %{token: token})
@@ -182,19 +191,15 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPI do
invite when valid_invite? ->
UserInviteToken.update_usage!(invite)
- create_user(params)
+ create_user(params, opts)
_ ->
{:error, "Expired token"}
end
end
- defp registration_process(true, params, _token) do
- create_user(params)
- end
-
- defp create_user(params) do
- changeset = User.register_changeset(%User{}, params)
+ defp create_user(params, opts) do
+ changeset = User.register_changeset(%User{}, params, opts)
case User.register(changeset) do
{:ok, user} ->
diff --git a/lib/pleroma/web/twitter_api/twitter_api_controller.ex b/lib/pleroma/web/twitter_api/twitter_api_controller.ex
index ef7b6fe65..3c5a70be9 100644
--- a/lib/pleroma/web/twitter_api/twitter_api_controller.ex
+++ b/lib/pleroma/web/twitter_api/twitter_api_controller.ex
@@ -182,6 +182,7 @@ defmodule Pleroma.Web.TwitterAPI.Controller do
|> Map.put("blocking_user", user)
|> Map.put("user", user)
|> Map.put(:visibility, "direct")
+ |> Map.put(:order, :desc)
activities =
ActivityPub.fetch_activities_query([user.ap_id], params)
@@ -439,7 +440,7 @@ defmodule Pleroma.Web.TwitterAPI.Controller do
true <- user.local,
true <- user.info.confirmation_pending,
true <- user.info.confirmation_token == token,
- info_change <- User.Info.confirmation_changeset(user.info, :confirmed),
+ info_change <- User.Info.confirmation_changeset(user.info, need_confirmation: false),
changeset <- Changeset.change(user) |> Changeset.put_embed(:info, info_change),
{:ok, _} <- User.update_and_set_cache(changeset) do
conn
diff --git a/lib/pleroma/web/twitter_api/views/activity_view.ex b/lib/pleroma/web/twitter_api/views/activity_view.ex
index c64152da8..d084ad734 100644
--- a/lib/pleroma/web/twitter_api/views/activity_view.ex
+++ b/lib/pleroma/web/twitter_api/views/activity_view.ex
@@ -170,7 +170,7 @@ defmodule Pleroma.Web.TwitterAPI.ActivityView do
created_at = activity.data["published"] |> Utils.date_to_asctime()
announced_activity = Activity.get_create_by_object_ap_id(activity.data["object"])
- text = "#{user.nickname} retweeted a status."
+ text = "#{user.nickname} repeated a status."
retweeted_status = render("activity.json", Map.merge(opts, %{activity: announced_activity}))
diff --git a/lib/pleroma/web/web_finger/web_finger.ex b/lib/pleroma/web/web_finger/web_finger.ex
index a3b0bf999..3a3b98a10 100644
--- a/lib/pleroma/web/web_finger/web_finger.ex
+++ b/lib/pleroma/web/web_finger/web_finger.ex
@@ -7,7 +7,7 @@ defmodule Pleroma.Web.WebFinger do
alias Pleroma.User
alias Pleroma.Web
- alias Pleroma.Web.OStatus
+ alias Pleroma.Web.Federator.Publisher
alias Pleroma.Web.Salmon
alias Pleroma.Web.XML
alias Pleroma.XmlBuilder
@@ -50,70 +50,40 @@ defmodule Pleroma.Web.WebFinger do
end
end
+ defp gather_links(%User{} = user) do
+ [
+ %{
+ "rel" => "http://webfinger.net/rel/profile-page",
+ "type" => "text/html",
+ "href" => user.ap_id
+ }
+ ] ++ Publisher.gather_webfinger_links(user)
+ end
+
def represent_user(user, "JSON") do
{:ok, user} = ensure_keys_present(user)
- {:ok, _private, public} = Salmon.keys_from_pem(user.info.keys)
- magic_key = Salmon.encode_key(public)
%{
"subject" => "acct:#{user.nickname}@#{Pleroma.Web.Endpoint.host()}",
"aliases" => [user.ap_id],
- "links" => [
- %{
- "rel" => "http://schemas.google.com/g/2010#updates-from",
- "type" => "application/atom+xml",
- "href" => OStatus.feed_path(user)
- },
- %{
- "rel" => "http://webfinger.net/rel/profile-page",
- "type" => "text/html",
- "href" => user.ap_id
- },
- %{"rel" => "salmon", "href" => OStatus.salmon_path(user)},
- %{
- "rel" => "magic-public-key",
- "href" => "data:application/magic-public-key,#{magic_key}"
- },
- %{"rel" => "self", "type" => "application/activity+json", "href" => user.ap_id},
- %{
- "rel" => "self",
- "type" => "application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\"",
- "href" => user.ap_id
- },
- %{
- "rel" => "http://ostatus.org/schema/1.0/subscribe",
- "template" => OStatus.remote_follow_path()
- }
- ]
+ "links" => gather_links(user)
}
end
def represent_user(user, "XML") do
{:ok, user} = ensure_keys_present(user)
- {:ok, _private, public} = Salmon.keys_from_pem(user.info.keys)
- magic_key = Salmon.encode_key(public)
+
+ links =
+ gather_links(user)
+ |> Enum.map(fn link -> {:Link, link} end)
{
:XRD,
%{xmlns: "http://docs.oasis-open.org/ns/xri/xrd-1.0"},
[
{:Subject, "acct:#{user.nickname}@#{Pleroma.Web.Endpoint.host()}"},
- {:Alias, user.ap_id},
- {:Link,
- %{
- rel: "http://schemas.google.com/g/2010#updates-from",
- type: "application/atom+xml",
- href: OStatus.feed_path(user)
- }},
- {:Link,
- %{rel: "http://webfinger.net/rel/profile-page", type: "text/html", href: user.ap_id}},
- {:Link, %{rel: "salmon", href: OStatus.salmon_path(user)}},
- {:Link,
- %{rel: "magic-public-key", href: "data:application/magic-public-key,#{magic_key}"}},
- {:Link, %{rel: "self", type: "application/activity+json", href: user.ap_id}},
- {:Link,
- %{rel: "http://ostatus.org/schema/1.0/subscribe", template: OStatus.remote_follow_path()}}
- ]
+ {:Alias, user.ap_id}
+ ] ++ links
}
|> XmlBuilder.to_doc()
end
diff --git a/lib/pleroma/web/websub/websub.ex b/lib/pleroma/web/websub/websub.ex
index 3ffa6b416..7ad0414ab 100644
--- a/lib/pleroma/web/websub/websub.ex
+++ b/lib/pleroma/web/websub/websub.ex
@@ -4,10 +4,14 @@
defmodule Pleroma.Web.Websub do
alias Ecto.Changeset
+ alias Pleroma.Activity
alias Pleroma.Instances
alias Pleroma.Repo
+ alias Pleroma.User
+ alias Pleroma.Web.ActivityPub.Visibility
alias Pleroma.Web.Endpoint
alias Pleroma.Web.Federator
+ alias Pleroma.Web.Federator.Publisher
alias Pleroma.Web.OStatus
alias Pleroma.Web.OStatus.FeedRepresenter
alias Pleroma.Web.Router.Helpers
@@ -18,6 +22,8 @@ defmodule Pleroma.Web.Websub do
import Ecto.Query
+ @behaviour Pleroma.Web.Federator.Publisher
+
@httpoison Application.get_env(:pleroma, :httpoison)
def verify(subscription, getter \\ &@httpoison.get/3) do
@@ -56,6 +62,13 @@ defmodule Pleroma.Web.Websub do
"Undo",
"Delete"
]
+
+ def is_representable?(%Activity{data: %{"type" => type}} = activity)
+ when type in @supported_activities,
+ do: Visibility.is_public?(activity)
+
+ def is_representable?(_), do: false
+
def publish(topic, user, %{data: %{"type" => type}} = activity)
when type in @supported_activities do
response =
@@ -88,12 +101,14 @@ defmodule Pleroma.Web.Websub do
unreachable_since: reachable_callbacks_metadata[sub.callback]
}
- Federator.publish_single_websub(data)
+ Publisher.enqueue_one(__MODULE__, data)
end)
end
def publish(_, _, _), do: ""
+ def publish(actor, activity), do: publish(Pleroma.Web.OStatus.feed_path(actor), actor, activity)
+
def sign(secret, doc) do
:crypto.hmac(:sha, secret, to_string(doc)) |> Base.encode16() |> String.downcase()
end
@@ -299,4 +314,20 @@ defmodule Pleroma.Web.Websub do
{:error, response}
end
end
+
+ def gather_webfinger_links(%User{} = user) do
+ [
+ %{
+ "rel" => "http://schemas.google.com/g/2010#updates-from",
+ "type" => "application/atom+xml",
+ "href" => OStatus.feed_path(user)
+ },
+ %{
+ "rel" => "http://ostatus.org/schema/1.0/subscribe",
+ "template" => OStatus.remote_follow_path()
+ }
+ ]
+ end
+
+ def gather_nodeinfo_protocol_names, do: ["ostatus"]
end