diff options
Diffstat (limited to 'lib/pleroma/web')
83 files changed, 1916 insertions, 899 deletions
diff --git a/lib/pleroma/web/activity_pub/activity_pub.ex b/lib/pleroma/web/activity_pub/activity_pub.ex index ed579e336..2d4cc9f68 100644 --- a/lib/pleroma/web/activity_pub/activity_pub.ex +++ b/lib/pleroma/web/activity_pub/activity_pub.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.ActivityPub.ActivityPub do alias Pleroma.{Activity, Repo, Object, Upload, User, Notification} alias Pleroma.Web.ActivityPub.{Transmogrifier, MRF} @@ -42,7 +46,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do defp check_actor_is_active(actor) do if not is_nil(actor) do with user <- User.get_cached_by_ap_id(actor), - false <- !!user.info["deactivated"] do + false <- user.info.deactivated do :ok else _e -> :reject @@ -499,6 +503,12 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do defp restrict_replies(query, _), do: query + defp restrict_reblogs(query, %{"exclude_reblogs" => val}) when val == "true" or val == "1" do + from(activity in query, where: fragment("?->>'type' != 'Announce'", activity.data)) + end + + defp restrict_reblogs(query, _), do: query + # Only search through last 100_000 activities by default defp restrict_recent(query, %{"whole_db" => true}), do: query @@ -509,8 +519,8 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do end defp restrict_blocked(query, %{"blocking_user" => %User{info: info}}) do - blocks = info["blocks"] || [] - domain_blocks = info["domain_blocks"] || [] + blocks = info.blocks || [] + domain_blocks = info.domain_blocks || [] from( activity in query, @@ -557,6 +567,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do |> restrict_media(opts) |> restrict_visibility(opts) |> restrict_replies(opts) + |> restrict_reblogs(opts) end def fetch_activities(recipients, opts \\ %{}) do @@ -572,11 +583,16 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do |> Enum.reverse() end - def upload(file, size_limit \\ nil) do - with data <- - Upload.store(file, Application.get_env(:pleroma, :instance)[:dedupe_media], size_limit), - false <- is_nil(data) do - Repo.insert(%Object{data: data}) + def upload(file, opts \\ []) do + with {:ok, data} <- Upload.store(file, opts) do + obj_data = + if opts[:actor] do + Map.put(data, "actor", opts[:actor]) + else + data + end + + Repo.insert(%Object{data: obj_data}) end end @@ -678,7 +694,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do remote_inboxes = (Pleroma.Web.Salmon.remote_users(activity) ++ followers) |> Enum.filter(fn user -> User.ap_enabled?(user) end) - |> Enum.map(fn %{info: %{"source_data" => data}} -> + |> Enum.map(fn %{info: %{source_data: data}} -> (is_map(data["endpoints"]) && Map.get(data["endpoints"], "sharedInbox")) || data["inbox"] end) |> Enum.uniq() @@ -764,13 +780,10 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do Logger.info("Fetching #{id} via AP") with true <- String.starts_with?(id, "http"), - {:ok, %{body: body, status_code: code}} when code in 200..299 <- + {:ok, %{body: body, status: code}} when code in 200..299 <- @httpoison.get( id, - [Accept: "application/activity+json"], - follow_redirect: true, - timeout: 10000, - recv_timeout: 20000 + [{:Accept, "application/activity+json"}] ), {:ok, data} <- Jason.decode(body), :ok <- Transmogrifier.contain_origin_from_id(id, data) do @@ -797,7 +810,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do end # guard - def entire_thread_visible_for_user?(nil, user), do: false + def entire_thread_visible_for_user?(nil, _user), do: false # child def entire_thread_visible_for_user?( diff --git a/lib/pleroma/web/activity_pub/activity_pub_controller.ex b/lib/pleroma/web/activity_pub/activity_pub_controller.ex index 3570a75cb..7fd6a45f5 100644 --- a/lib/pleroma/web/activity_pub/activity_pub_controller.ex +++ b/lib/pleroma/web/activity_pub/activity_pub_controller.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.ActivityPub.ActivityPubController do use Pleroma.Web, :controller alias Pleroma.{User, Object} @@ -141,7 +145,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubController do json(conn, "error") end - def relay(conn, params) do + def relay(conn, _params) do with %User{} = user <- Relay.get_actor(), {:ok, user} <- Pleroma.Web.WebFinger.ensure_keys_present(user) do conn diff --git a/lib/pleroma/web/activity_pub/mrf.ex b/lib/pleroma/web/activity_pub/mrf.ex index 0a4e2bf80..00919a5f6 100644 --- a/lib/pleroma/web/activity_pub/mrf.ex +++ b/lib/pleroma/web/activity_pub/mrf.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.ActivityPub.MRF do @callback filter(Map.t()) :: {:ok | :reject, Map.t()} diff --git a/lib/pleroma/web/activity_pub/mrf/drop_policy.ex b/lib/pleroma/web/activity_pub/mrf/drop_policy.ex index 811947943..6ac7b0ec1 100644 --- a/lib/pleroma/web/activity_pub/mrf/drop_policy.ex +++ b/lib/pleroma/web/activity_pub/mrf/drop_policy.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.ActivityPub.MRF.DropPolicy do require Logger @behaviour Pleroma.Web.ActivityPub.MRF diff --git a/lib/pleroma/web/activity_pub/mrf/ensure_re_prepended.ex b/lib/pleroma/web/activity_pub/mrf/ensure_re_prepended.ex new file mode 100644 index 000000000..ca3ee8a0d --- /dev/null +++ b/lib/pleroma/web/activity_pub/mrf/ensure_re_prepended.ex @@ -0,0 +1,44 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.Web.ActivityPub.MRF.EnsureRePrepended do + alias Pleroma.Object + + @behaviour Pleroma.Web.ActivityPub.MRF + + @reply_prefix Regex.compile!("^re:[[:space:]]*", [:caseless]) + def filter_by_summary( + %{"summary" => parent_summary} = _parent, + %{"summary" => child_summary} = child + ) + when not is_nil(child_summary) and byte_size(child_summary) > 0 and + not is_nil(parent_summary) and byte_size(parent_summary) > 0 do + if (child_summary == parent_summary and not Regex.match?(@reply_prefix, child_summary)) or + (Regex.match?(@reply_prefix, parent_summary) && + Regex.replace(@reply_prefix, parent_summary, "") == child_summary) do + Map.put(child, "summary", "re: " <> child_summary) + else + child + end + end + + def filter_by_summary(_parent, child), do: child + + def filter(%{"type" => activity_type} = object) when activity_type == "Create" do + child = object["object"] + in_reply_to = Object.normalize(child["inReplyTo"]) + + child = + if(in_reply_to, + do: filter_by_summary(in_reply_to.data, child), + else: child + ) + + object = Map.put(object, "object", child) + + {:ok, object} + end + + def filter(object), do: {:ok, object} +end diff --git a/lib/pleroma/web/activity_pub/mrf/hellthread_policy.ex b/lib/pleroma/web/activity_pub/mrf/hellthread_policy.ex new file mode 100644 index 000000000..e4fb0b5b0 --- /dev/null +++ b/lib/pleroma/web/activity_pub/mrf/hellthread_policy.ex @@ -0,0 +1,22 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.Web.ActivityPub.MRF.HellthreadPolicy do + @behaviour Pleroma.Web.ActivityPub.MRF + + @impl true + def filter(%{"type" => "Create"} = object) do + threshold = Pleroma.Config.get([:mrf_hellthread, :threshold]) + recipients = (object["to"] || []) ++ (object["cc"] || []) + + if length(recipients) > threshold do + {:reject, nil} + else + {:ok, object} + end + end + + @impl true + def filter(object), do: {:ok, object} +end diff --git a/lib/pleroma/web/activity_pub/mrf/noop_policy.ex b/lib/pleroma/web/activity_pub/mrf/noop_policy.ex index e26f60d26..8eacc62bc 100644 --- a/lib/pleroma/web/activity_pub/mrf/noop_policy.ex +++ b/lib/pleroma/web/activity_pub/mrf/noop_policy.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.ActivityPub.MRF.NoOpPolicy do @behaviour Pleroma.Web.ActivityPub.MRF diff --git a/lib/pleroma/web/activity_pub/mrf/normalize_markup.ex b/lib/pleroma/web/activity_pub/mrf/normalize_markup.ex index c53cb1ad2..6cfd43974 100644 --- a/lib/pleroma/web/activity_pub/mrf/normalize_markup.ex +++ b/lib/pleroma/web/activity_pub/mrf/normalize_markup.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.ActivityPub.MRF.NormalizeMarkup do alias Pleroma.HTML 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 627284083..07d739437 100644 --- a/lib/pleroma/web/activity_pub/mrf/reject_non_public.ex +++ b/lib/pleroma/web/activity_pub/mrf/reject_non_public.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.ActivityPub.MRF.RejectNonPublic do alias Pleroma.User @behaviour Pleroma.Web.ActivityPub.MRF diff --git a/lib/pleroma/web/activity_pub/mrf/simple_policy.ex b/lib/pleroma/web/activity_pub/mrf/simple_policy.ex index 86dcf5080..9ced1e620 100644 --- a/lib/pleroma/web/activity_pub/mrf/simple_policy.ex +++ b/lib/pleroma/web/activity_pub/mrf/simple_policy.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicy do alias Pleroma.User @behaviour Pleroma.Web.ActivityPub.MRF @@ -23,7 +27,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicy do defp check_media_removal( %{host: actor_host} = _actor_info, - %{"type" => "Create", "object" => %{"attachement" => child_attachment}} = object + %{"type" => "Create", "object" => %{"attachment" => child_attachment}} = object ) when length(child_attachment) > 0 do object = diff --git a/lib/pleroma/web/activity_pub/mrf/user_allowlist.ex b/lib/pleroma/web/activity_pub/mrf/user_allowlist.ex new file mode 100644 index 000000000..7a78c50bf --- /dev/null +++ b/lib/pleroma/web/activity_pub/mrf/user_allowlist.ex @@ -0,0 +1,27 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.Web.ActivityPub.MRF.UserAllowListPolicy do + alias Pleroma.Config + + @behaviour Pleroma.Web.ActivityPub.MRF + + defp filter_by_list(object, []), do: {:ok, object} + + defp filter_by_list(%{"actor" => actor} = object, allow_list) do + if actor in allow_list do + {:ok, object} + else + {:reject, nil} + end + end + + @impl true + def filter(object) do + actor_info = URI.parse(object["actor"]) + allow_list = Config.get([:mrf_user_allowlist, String.to_atom(actor_info.host)], []) + + filter_by_list(object, allow_list) + end +end diff --git a/lib/pleroma/web/activity_pub/relay.ex b/lib/pleroma/web/activity_pub/relay.ex index fcdc6b1c0..d0a866589 100644 --- a/lib/pleroma/web/activity_pub/relay.ex +++ b/lib/pleroma/web/activity_pub/relay.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.ActivityPub.Relay do alias Pleroma.{User, Object, Activity} alias Pleroma.Web.ActivityPub.ActivityPub diff --git a/lib/pleroma/web/activity_pub/transmogrifier.ex b/lib/pleroma/web/activity_pub/transmogrifier.ex index 5864855b0..315571e1a 100644 --- a/lib/pleroma/web/activity_pub/transmogrifier.ex +++ b/lib/pleroma/web/activity_pub/transmogrifier.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.ActivityPub.Transmogrifier do @moduledoc """ A module to handle coding from internal to wire ActivityPub and back. @@ -37,9 +41,9 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do @doc """ Checks that an imported AP object's actor matches the domain it came from. """ - def contain_origin(id, %{"actor" => nil}), do: :error + def contain_origin(_id, %{"actor" => nil}), do: :error - def contain_origin(id, %{"actor" => actor} = params) do + def contain_origin(id, %{"actor" => _actor} = params) do id_uri = URI.parse(id) actor_uri = URI.parse(get_actor(params)) @@ -50,9 +54,9 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do end end - def contain_origin_from_id(id, %{"id" => nil}), do: :error + def contain_origin_from_id(_id, %{"id" => nil}), do: :error - def contain_origin_from_id(id, %{"id" => other_id} = params) do + def contain_origin_from_id(id, %{"id" => other_id} = _params) do id_uri = URI.parse(id) other_uri = URI.parse(other_id) @@ -69,8 +73,8 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do def fix_object(object) do object |> fix_actor - |> fix_attachments |> fix_url + |> fix_attachments |> fix_context |> fix_in_reply_to |> fix_emoji @@ -170,8 +174,14 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do attachments = attachment |> Enum.map(fn data -> - url = [%{"type" => "Link", "mediaType" => data["mediaType"], "href" => data["url"]}] - Map.put(data, "url", url) + media_type = data["mediaType"] || data["mimeType"] + href = data["url"] || data["href"] + + url = [%{"type" => "Link", "mediaType" => media_type, "href" => href}] + + data + |> Map.put("mediaType", media_type) + |> Map.put("url", url) end) object @@ -190,7 +200,22 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do |> Map.put("url", url["href"]) end - def fix_url(%{"url" => url} = object) when is_list(url) do + def fix_url(%{"type" => "Video", "url" => url} = object) when is_list(url) do + first_element = Enum.at(url, 0) + + link_element = + url + |> Enum.filter(fn x -> is_map(x) end) + |> Enum.filter(fn x -> x["mimeType"] == "text/html" end) + |> Enum.at(0) + + object + |> Map.put("attachment", [first_element]) + |> Map.put("url", link_element["href"]) + end + + def fix_url(%{"type" => object_type, "url" => url} = object) + when object_type != "Video" and is_list(url) do first_element = Enum.at(url, 0) url_string = @@ -266,6 +291,32 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do def fix_content_map(object), do: object + defp mastodon_follow_hack(%{"id" => id, "actor" => follower_id}, followed) do + with true <- id =~ "follows", + %User{local: true} = follower <- User.get_cached_by_ap_id(follower_id), + %Activity{} = activity <- Utils.fetch_latest_follow(follower, followed) do + {:ok, activity} + else + _ -> {:error, nil} + end + end + + defp mastodon_follow_hack(_, _), do: {:error, nil} + + defp get_follow_activity(follow_object, followed) do + with object_id when not is_nil(object_id) <- Utils.get_ap_id(follow_object), + {_, %Activity{} = activity} <- {:activity, Activity.get_by_ap_id(object_id)} do + {:ok, activity} + else + # Can't find the activity. This might a Mastodon 2.3 "Accept" + {:activity, nil} -> + mastodon_follow_hack(follow_object, followed) + + _ -> + {:error, nil} + end + end + # disallow objects with bogus IDs def handle_incoming(%{"id" => nil}), do: :error def handle_incoming(%{"id" => ""}), do: :error @@ -331,34 +382,8 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do end end - defp mastodon_follow_hack(%{"id" => id, "actor" => follower_id}, followed) do - with true <- id =~ "follows", - %User{local: true} = follower <- User.get_cached_by_ap_id(follower_id), - %Activity{} = activity <- Utils.fetch_latest_follow(follower, followed) do - {:ok, activity} - else - _ -> {:error, nil} - end - end - - defp mastodon_follow_hack(_), do: {:error, nil} - - defp get_follow_activity(follow_object, followed) do - with object_id when not is_nil(object_id) <- Utils.get_ap_id(follow_object), - {_, %Activity{} = activity} <- {:activity, Activity.get_by_ap_id(object_id)} do - {:ok, activity} - else - # Can't find the activity. This might a Mastodon 2.3 "Accept" - {:activity, nil} -> - mastodon_follow_hack(follow_object, followed) - - _ -> - {:error, nil} - end - end - def handle_incoming( - %{"type" => "Accept", "object" => follow_object, "actor" => actor, "id" => id} = data + %{"type" => "Accept", "object" => follow_object, "actor" => _actor, "id" => _id} = data ) do with actor <- get_actor(data), %User{} = followed <- User.get_or_fetch_by_ap_id(actor), @@ -374,7 +399,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do local: false }) do if not User.following?(follower, followed) do - {:ok, follower} = User.follow(follower, followed) + {:ok, _follower} = User.follow(follower, followed) end {:ok, activity} @@ -384,7 +409,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do end def handle_incoming( - %{"type" => "Reject", "object" => follow_object, "actor" => actor, "id" => id} = data + %{"type" => "Reject", "object" => follow_object, "actor" => _actor, "id" => _id} = data ) do with actor <- get_actor(data), %User{} = followed <- User.get_or_fetch_by_ap_id(actor), @@ -408,7 +433,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do end def handle_incoming( - %{"type" => "Like", "object" => object_id, "actor" => actor, "id" => id} = data + %{"type" => "Like", "object" => object_id, "actor" => _actor, "id" => id} = data ) do with actor <- get_actor(data), %User{} = actor <- User.get_or_fetch_by_ap_id(actor), @@ -421,7 +446,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do end def handle_incoming( - %{"type" => "Announce", "object" => object_id, "actor" => actor, "id" => id} = data + %{"type" => "Announce", "object" => object_id, "actor" => _actor, "id" => id} = data ) do with actor <- get_actor(data), %User{} = actor <- User.get_or_fetch_by_ap_id(actor), @@ -447,7 +472,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do update_data = new_user_data |> Map.take([:name, :bio, :avatar]) - |> Map.put(:info, Map.merge(actor.info, %{"banner" => banner, "locked" => locked})) + |> Map.put(:info, %{"banner" => banner, "locked" => locked}) actor |> User.upgrade_changeset(update_data) @@ -492,7 +517,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do %{ "type" => "Undo", "object" => %{"type" => "Announce", "object" => object_id}, - "actor" => actor, + "actor" => _actor, "id" => id } = data ) do @@ -520,7 +545,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do User.unfollow(follower, followed) {:ok, activity} else - e -> :error + _e -> :error end end @@ -539,12 +564,12 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do User.unblock(blocker, blocked) {:ok, activity} else - e -> :error + _e -> :error end end def handle_incoming( - %{"type" => "Block", "object" => blocked, "actor" => blocker, "id" => id} = data + %{"type" => "Block", "object" => blocked, "actor" => blocker, "id" => id} = _data ) do with true <- Pleroma.Config.get([:activitypub, :accept_blocks]), %User{local: true} = blocked = User.get_cached_by_ap_id(blocked), @@ -554,7 +579,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do User.block(blocker, blocked) {:ok, activity} else - e -> :error + _e -> :error end end @@ -562,7 +587,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do %{ "type" => "Undo", "object" => %{"type" => "Like", "object" => object_id}, - "actor" => actor, + "actor" => _actor, "id" => id } = data ) do @@ -850,10 +875,6 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do def upgrade_user_from_ap_id(ap_id, async \\ true) do with %User{local: false} = user <- User.get_by_ap_id(ap_id), {:ok, data} <- ActivityPub.fetch_and_prepare_user_from_ap_id(ap_id) do - data = - data - |> Map.put(:info, Map.merge(user.info, data[:info])) - already_ap = User.ap_enabled?(user) {:ok, user} = diff --git a/lib/pleroma/web/activity_pub/utils.ex b/lib/pleroma/web/activity_pub/utils.ex index 549148989..59cf6abfc 100644 --- a/lib/pleroma/web/activity_pub/utils.ex +++ b/lib/pleroma/web/activity_pub/utils.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.ActivityPub.Utils do alias Pleroma.{Repo, Web, Object, Activity, User, Notification} alias Pleroma.Web.Router.Helpers @@ -292,7 +296,7 @@ defmodule Pleroma.Web.ActivityPub.Utils do """ def make_follow_data( %User{ap_id: follower_id}, - %User{ap_id: followed_id} = followed, + %User{ap_id: followed_id} = _followed, activity_id ) do data = %{ diff --git a/lib/pleroma/web/activity_pub/views/object_view.ex b/lib/pleroma/web/activity_pub/views/object_view.ex index ff664636c..efe16b2bf 100644 --- a/lib/pleroma/web/activity_pub/views/object_view.ex +++ b/lib/pleroma/web/activity_pub/views/object_view.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.ActivityPub.ObjectView do use Pleroma.Web, :view alias Pleroma.{Object, Activity} diff --git a/lib/pleroma/web/activity_pub/views/user_view.ex b/lib/pleroma/web/activity_pub/views/user_view.ex index eb335813d..f0c268755 100644 --- a/lib/pleroma/web/activity_pub/views/user_view.ex +++ b/lib/pleroma/web/activity_pub/views/user_view.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.ActivityPub.UserView do use Pleroma.Web, :view alias Pleroma.Web.Salmon @@ -12,7 +16,7 @@ defmodule Pleroma.Web.ActivityPub.UserView do # the instance itself is not a Person, but instead an Application def render("user.json", %{user: %{nickname: nil} = user}) do {:ok, user} = WebFinger.ensure_keys_present(user) - {:ok, _, public_key} = Salmon.keys_from_pem(user.info["keys"]) + {:ok, _, public_key} = Salmon.keys_from_pem(user.info.keys) public_key = :public_key.pem_entry_encode(:SubjectPublicKeyInfo, public_key) public_key = :public_key.pem_encode([public_key]) @@ -40,7 +44,7 @@ defmodule Pleroma.Web.ActivityPub.UserView do def render("user.json", %{user: user}) do {:ok, user} = WebFinger.ensure_keys_present(user) - {:ok, _, public_key} = Salmon.keys_from_pem(user.info["keys"]) + {:ok, _, public_key} = Salmon.keys_from_pem(user.info.keys) public_key = :public_key.pem_entry_encode(:SubjectPublicKeyInfo, public_key) public_key = :public_key.pem_encode([public_key]) @@ -55,7 +59,7 @@ defmodule Pleroma.Web.ActivityPub.UserView do "name" => user.name, "summary" => user.bio, "url" => user.ap_id, - "manuallyApprovesFollowers" => user.info["locked"] || false, + "manuallyApprovesFollowers" => user.info.locked, "publicKey" => %{ "id" => "#{user.ap_id}#main-key", "owner" => user.ap_id, @@ -72,7 +76,7 @@ defmodule Pleroma.Web.ActivityPub.UserView do "type" => "Image", "url" => User.banner_url(user) }, - "tag" => user.info["source_data"]["tag"] || [] + "tag" => user.info.source_data["tag"] || [] } |> Map.merge(Utils.make_json_ld_header()) end @@ -82,7 +86,7 @@ defmodule Pleroma.Web.ActivityPub.UserView do query = from(user in query, select: [:ap_id]) following = Repo.all(query) - collection(following, "#{user.ap_id}/following", page) + collection(following, "#{user.ap_id}/following", page, !user.info.hide_network) |> Map.merge(Utils.make_json_ld_header()) end @@ -95,7 +99,7 @@ defmodule Pleroma.Web.ActivityPub.UserView do "id" => "#{user.ap_id}/following", "type" => "OrderedCollection", "totalItems" => length(following), - "first" => collection(following, "#{user.ap_id}/following", 1) + "first" => collection(following, "#{user.ap_id}/following", 1, !user.info.hide_network) } |> Map.merge(Utils.make_json_ld_header()) end @@ -105,7 +109,7 @@ defmodule Pleroma.Web.ActivityPub.UserView do query = from(user in query, select: [:ap_id]) followers = Repo.all(query) - collection(followers, "#{user.ap_id}/followers", page) + collection(followers, "#{user.ap_id}/followers", page, !user.info.hide_network) |> Map.merge(Utils.make_json_ld_header()) end @@ -118,7 +122,7 @@ defmodule Pleroma.Web.ActivityPub.UserView do "id" => "#{user.ap_id}/followers", "type" => "OrderedCollection", "totalItems" => length(followers), - "first" => collection(followers, "#{user.ap_id}/followers", 1) + "first" => collection(followers, "#{user.ap_id}/followers", 1, !user.info.hide_network) } |> Map.merge(Utils.make_json_ld_header()) end @@ -172,7 +176,7 @@ defmodule Pleroma.Web.ActivityPub.UserView do end end - def collection(collection, iri, page, total \\ nil) do + def collection(collection, iri, page, show_items \\ true, total \\ nil) do offset = (page - 1) * 10 items = Enum.slice(collection, offset, 10) items = Enum.map(items, fn user -> user.ap_id end) @@ -183,7 +187,7 @@ defmodule Pleroma.Web.ActivityPub.UserView do "type" => "OrderedCollectionPage", "partOf" => iri, "totalItems" => total, - "orderedItems" => items + "orderedItems" => if(show_items, do: items, else: []) } if offset < total do diff --git a/lib/pleroma/web/admin_api/admin_api_controller.ex b/lib/pleroma/web/admin_api/admin_api_controller.ex index bcdb4ba37..49d237661 100644 --- a/lib/pleroma/web/admin_api/admin_api_controller.ex +++ b/lib/pleroma/web/admin_api/admin_api_controller.ex @@ -1,8 +1,14 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.AdminAPI.AdminAPIController do use Pleroma.Web, :controller - alias Pleroma.{User, Repo} + alias Pleroma.User alias Pleroma.Web.ActivityPub.Relay + import Pleroma.Web.ControllerHelper, only: [json_response: 3] + require Logger action_fallback(:errors) @@ -24,7 +30,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIController do conn, %{"nickname" => nickname, "email" => email, "password" => password} ) do - new_user = %{ + user_data = %{ nickname: nickname, name: nickname, email: email, @@ -33,11 +39,21 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIController do bio: "." } - User.register_changeset(%User{}, new_user) - |> Repo.insert!() + changeset = User.register_changeset(%User{}, user_data, confirmed: true) + {:ok, user} = User.register(changeset) conn - |> json(new_user.nickname) + |> json(user.nickname) + end + + def tag_users(conn, %{"nicknames" => nicknames, "tags" => tags}) do + with {:ok, _} <- User.tag(nicknames, tags), + do: json_response(conn, :no_content, "") + end + + def untag_users(conn, %{"nicknames" => nicknames, "tags" => tags}) do + with {:ok, _} <- User.untag(nicknames, tags), + do: json_response(conn, :no_content, "") end def right_add(conn, %{"permission_group" => permission_group, "nickname" => nickname}) @@ -45,21 +61,19 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIController do user = User.get_by_nickname(nickname) info = - user.info + %{} |> Map.put("is_" <> permission_group, true) - cng = User.info_changeset(user, %{info: info}) - {:ok, user} = User.update_and_set_cache(cng) + info_cng = User.Info.admin_api_update(user.info, info) - conn - |> json(user.info) - end + cng = + user + |> Ecto.Changeset.change() + |> Ecto.Changeset.put_embed(:info, info_cng) - def right_get(conn, %{"nickname" => nickname}) do - user = User.get_by_nickname(nickname) + {:ok, _user} = User.update_and_set_cache(cng) - conn - |> json(user.info) + json(conn, info) end def right_add(conn, _) do @@ -68,6 +82,16 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIController do |> json(%{error: "No such permission_group"}) end + def right_get(conn, %{"nickname" => nickname}) do + user = User.get_by_nickname(nickname) + + conn + |> json(%{ + is_moderator: user.info.is_moderator, + is_admin: user.info.is_admin + }) + end + def right_delete( %{assigns: %{user: %User{:nickname => admin_nickname}}} = conn, %{ @@ -84,14 +108,18 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIController do user = User.get_by_nickname(nickname) info = - user.info + %{} |> Map.put("is_" <> permission_group, false) - cng = User.info_changeset(user, %{info: info}) - {:ok, user} = User.update_and_set_cache(cng) + info_cng = User.Info.admin_api_update(user.info, info) - conn - |> json(user.info) + cng = + Ecto.Changeset.change(user) + |> Ecto.Changeset.put_embed(:info, info_cng) + + {:ok, _user} = User.update_and_set_cache(cng) + + json(conn, info) end end @@ -102,32 +130,41 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIController do end def relay_follow(conn, %{"relay_url" => target}) do - {status, message} = Relay.follow(target) - - if status == :ok do - conn - |> json(target) + with {:ok, _message} <- Relay.follow(target) do + json(conn, target) else - conn - |> put_status(500) - |> json(target) + _ -> + conn + |> put_status(500) + |> json(target) end end def relay_unfollow(conn, %{"relay_url" => target}) do - {status, message} = Relay.unfollow(target) - - if status == :ok do - conn - |> json(target) + with {:ok, _message} <- Relay.unfollow(target) do + json(conn, target) else - conn - |> put_status(500) - |> json(target) + _ -> + conn + |> put_status(500) + |> json(target) + end + end + + @doc "Sends registration invite via email" + def email_invite(%{assigns: %{user: user}} = conn, %{"email" => email} = params) do + with true <- + Pleroma.Config.get([:instance, :invites_enabled]) && + !Pleroma.Config.get([:instance, :registrations_open]), + {:ok, invite_token} <- Pleroma.UserInviteToken.create_token(), + email <- + Pleroma.UserEmail.user_invitation_email(user, invite_token, email, params["name"]), + {:ok, _} <- Pleroma.Mailer.deliver(email) do + json_response(conn, :no_content, "") end end - @shortdoc "Get a account registeration invite token (base64 string)" + @doc "Get a account registeration invite token (base64 string)" def get_invite_token(conn, _params) do {:ok, token} = Pleroma.UserInviteToken.create_token() @@ -135,7 +172,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIController do |> json(token.token) end - @shortdoc "Get a password reset token (base64 string) for given nickname" + @doc "Get a password reset token (base64 string) for given nickname" def get_password_reset(conn, %{"nickname" => nickname}) do (%User{local: true} = user) = User.get_by_nickname(nickname) {:ok, token} = Pleroma.PasswordResetToken.create_token(user) diff --git a/lib/pleroma/web/channels/user_socket.ex b/lib/pleroma/web/channels/user_socket.ex index 07ddee169..23ba5a381 100644 --- a/lib/pleroma/web/channels/user_socket.ex +++ b/lib/pleroma/web/channels/user_socket.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.UserSocket do use Phoenix.Socket alias Pleroma.User @@ -6,10 +10,6 @@ defmodule Pleroma.Web.UserSocket do # channel "room:*", Pleroma.Web.RoomChannel channel("chat:*", Pleroma.Web.ChatChannel) - ## Transports - transport(:websocket, Phoenix.Transports.WebSocket) - # transport :longpoll, Phoenix.Transports.LongPoll - # Socket params are passed from the client and can # be used to verify and authenticate a user. After # verification, you can put default assigns into diff --git a/lib/pleroma/web/chat_channel.ex b/lib/pleroma/web/chat_channel.ex index 37eba8c3f..ac28f300b 100644 --- a/lib/pleroma/web/chat_channel.ex +++ b/lib/pleroma/web/chat_channel.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.ChatChannel do use Phoenix.Channel alias Pleroma.Web.ChatChannel.ChatChannelState diff --git a/lib/pleroma/web/common_api/common_api.ex b/lib/pleroma/web/common_api/common_api.ex index 77e4dbbd7..085a95172 100644 --- a/lib/pleroma/web/common_api/common_api.ex +++ b/lib/pleroma/web/common_api/common_api.ex @@ -1,6 +1,11 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.CommonAPI do alias Pleroma.{User, Repo, Activity, Object} alias Pleroma.Web.ActivityPub.ActivityPub + alias Pleroma.Web.ActivityPub.Utils alias Pleroma.Formatter import Pleroma.Web.CommonAPI.Utils @@ -8,7 +13,7 @@ defmodule Pleroma.Web.CommonAPI do def delete(activity_id, user) do with %Activity{data: %{"object" => %{"id" => object_id}}} <- Repo.get(Activity, activity_id), %Object{} = object <- Object.normalize(object_id), - true <- user.info["is_moderator"] || user.ap_id == object.data["actor"], + true <- user.info.is_moderator || user.ap_id == object.data["actor"], {:ok, delete} <- ActivityPub.delete(object) do {:ok, delete} end @@ -16,7 +21,8 @@ defmodule Pleroma.Web.CommonAPI do def repeat(id_or_ap_id, user) do with %Activity{} = activity <- get_by_id_or_ap_id(id_or_ap_id), - object <- Object.normalize(activity.data["object"]["id"]) do + object <- Object.normalize(activity.data["object"]["id"]), + nil <- Utils.get_existing_announce(user.ap_id, object) do ActivityPub.announce(user, object) else _ -> @@ -36,7 +42,8 @@ defmodule Pleroma.Web.CommonAPI do def favorite(id_or_ap_id, user) do with %Activity{} = activity <- get_by_id_or_ap_id(id_or_ap_id), - object <- Object.normalize(activity.data["object"]["id"]) do + object <- Object.normalize(activity.data["object"]["id"]), + nil <- Utils.get_existing_like(user.ap_id, object) do ActivityPub.like(user, object) else _ -> @@ -95,7 +102,7 @@ defmodule Pleroma.Web.CommonAPI do attachments, tags, get_content_type(data["content_type"]), - data["no_attachment_links"] + Enum.member?([true, "true"], data["no_attachment_links"]) ), context <- make_context(inReplyTo), cw <- data["spoiler_text"], @@ -135,12 +142,13 @@ defmodule Pleroma.Web.CommonAPI do end end + # Updates the emojis for a user based on their profile def update(user) do user = with emoji <- emoji_from_profile(user), - source_data <- (user.info["source_data"] || %{}) |> Map.put("tag", emoji), - new_info <- Map.put(user.info, "source_data", source_data), - change <- User.info_changeset(user, %{info: new_info}), + source_data <- (user.info.source_data || %{}) |> Map.put("tag", emoji), + info_cng <- Pleroma.User.Info.set_source_data(user.info, source_data), + change <- Ecto.Changeset.change(user) |> Ecto.Changeset.put_embed(:info, info_cng), {:ok, user} <- User.update_and_set_cache(change) do user else diff --git a/lib/pleroma/web/common_api/utils.ex b/lib/pleroma/web/common_api/utils.ex index 728f24c7e..b91cfc4bb 100644 --- a/lib/pleroma/web/common_api/utils.ex +++ b/lib/pleroma/web/common_api/utils.ex @@ -1,11 +1,16 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.CommonAPI.Utils do - alias Pleroma.{Repo, Object, Formatter, Activity} + alias Calendar.Strftime + alias Comeonin.Pbkdf2 + alias Pleroma.{Activity, Formatter, Object, Repo} + alias Pleroma.User + alias Pleroma.Web alias Pleroma.Web.ActivityPub.Utils alias Pleroma.Web.Endpoint alias Pleroma.Web.MediaProxy - alias Pleroma.User - alias Calendar.Strftime - alias Comeonin.Pbkdf2 # This is a hack for twidere. def get_by_id_or_ap_id(id) do @@ -111,6 +116,9 @@ defmodule Pleroma.Web.CommonAPI.Utils do Enum.join([text | attachment_text], "<br>") end + @doc """ + Formatting text to plain text. + """ def format_input(text, mentions, tags, "text/plain") do text |> Formatter.html_escape("text/plain") @@ -122,7 +130,10 @@ defmodule Pleroma.Web.CommonAPI.Utils do |> Formatter.finalize() end - def format_input(text, mentions, tags, "text/html") do + @doc """ + Formatting text to html. + """ + def format_input(text, mentions, _tags, "text/html") do text |> Formatter.html_escape("text/html") |> String.replace(~r/\r?\n/, "<br>") @@ -131,8 +142,12 @@ defmodule Pleroma.Web.CommonAPI.Utils do |> Formatter.finalize() end + @doc """ + Formatting text to markdown. + """ def format_input(text, mentions, tags, "text/markdown") do text + |> Formatter.mentions_escape(mentions) |> Earmark.as_html!() |> Formatter.html_escape("text/html") |> String.replace(~r/\r?\n/, "") @@ -148,7 +163,7 @@ defmodule Pleroma.Web.CommonAPI.Utils do |> Enum.sort_by(fn {tag, _} -> -String.length(tag) end) Enum.reduce(tags, text, fn {full, tag}, text -> - url = "<a href='#{Pleroma.Web.base_url()}/tag/#{tag}' rel='tag'>##{tag}</a>" + url = "<a href='#{Web.base_url()}/tag/#{tag}' rel='tag'>##{tag}</a>" String.replace(text, full, url) end) end @@ -236,7 +251,7 @@ defmodule Pleroma.Web.CommonAPI.Utils do end end - def emoji_from_profile(%{info: info} = user) do + def emoji_from_profile(%{info: _info} = user) do (Formatter.get_emoji(user.bio) ++ Formatter.get_emoji(user.name)) |> Enum.map(fn {shortcode, url} -> %{ diff --git a/lib/pleroma/web/controller_helper.ex b/lib/pleroma/web/controller_helper.ex new file mode 100644 index 000000000..cb0463eeb --- /dev/null +++ b/lib/pleroma/web/controller_helper.ex @@ -0,0 +1,13 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.Web.ControllerHelper do + use Pleroma.Web, :controller + + def json_response(conn, status, json) do + conn + |> put_status(status) + |> json(json) + end +end diff --git a/lib/pleroma/web/endpoint.ex b/lib/pleroma/web/endpoint.ex index 8728c908b..e994f8f37 100644 --- a/lib/pleroma/web/endpoint.ex +++ b/lib/pleroma/web/endpoint.ex @@ -1,10 +1,12 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.Endpoint do use Phoenix.Endpoint, otp_app: :pleroma socket("/socket", Pleroma.Web.UserSocket) - socket("/api/v1", Pleroma.Web.MastodonAPI.MastodonSocket) - # Serve at "/" the static files from "priv/static" directory. # # You should set gzip to true if you are running phoenix.digest @@ -12,14 +14,18 @@ defmodule Pleroma.Web.Endpoint do plug(CORSPlug) plug(Pleroma.Plugs.HTTPSecurityPlug) - plug(Plug.Static, at: "/media", from: Pleroma.Uploaders.Local.upload_path(), gzip: false) + plug(Pleroma.Plugs.UploadedMedia) + + # InstanceStatic needs to be before Plug.Static to be able to override shipped-static files + # If you're adding new paths to `only:` you'll need to configure them in InstanceStatic as well + plug(Pleroma.Plugs.InstanceStatic, at: "/") plug( Plug.Static, at: "/", from: :pleroma, only: - ~w(index.html static finmoji emoji packs sounds images instance sw.js favicon.png schemas) + ~w(index.html static finmoji emoji packs sounds images instance sw.js favicon.png schemas doc) ) # Code reloading can be explicitly enabled under the diff --git a/lib/pleroma/web/federator/federator.ex b/lib/pleroma/web/federator/federator.ex index ac3d7c132..3aec55274 100644 --- a/lib/pleroma/web/federator/federator.ex +++ b/lib/pleroma/web/federator/federator.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.Federator do use GenServer alias Pleroma.User @@ -13,7 +17,6 @@ defmodule Pleroma.Web.Federator do @websub Application.get_env(:pleroma, :websub) @ostatus Application.get_env(:pleroma, :ostatus) - @httpoison Application.get_env(:pleroma, :httpoison) @max_jobs 20 def init(args) do @@ -134,7 +137,7 @@ defmodule Pleroma.Web.Federator do def handle( :publish_single_websub, - %{xml: xml, topic: topic, callback: callback, secret: secret} = params + %{xml: _xml, topic: _topic, callback: _callback, secret: _secret} = params ) do case Websub.publish_one(params) do {:ok, _} -> @@ -151,7 +154,7 @@ defmodule Pleroma.Web.Federator do end if Mix.env() == :test do - def enqueue(type, payload, priority \\ 1) do + def enqueue(type, payload, _priority \\ 1) do if Pleroma.Config.get([:instance, :federating]) do handle(type, payload) end diff --git a/lib/pleroma/web/federator/retry_queue.ex b/lib/pleroma/web/federator/retry_queue.ex index 06c094f26..5f1d43008 100644 --- a/lib/pleroma/web/federator/retry_queue.ex +++ b/lib/pleroma/web/federator/retry_queue.ex @@ -1,13 +1,12 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.Federator.RetryQueue do use GenServer - alias Pleroma.Web.{WebFinger, Websub} - alias Pleroma.Web.ActivityPub.ActivityPub + require Logger - @websub Application.get_env(:pleroma, :websub) - @ostatus Application.get_env(:pleroma, :websub) - @httpoison Application.get_env(:pleroma, :websub) - @instance Application.get_env(:pleroma, :websub) # initial timeout, 5 min @initial_timeout 30_000 @max_retries 5 @@ -17,7 +16,15 @@ defmodule Pleroma.Web.Federator.RetryQueue do end def start_link() do - GenServer.start_link(__MODULE__, %{delivered: 0, dropped: 0}, name: __MODULE__) + enabled = Pleroma.Config.get([:retry_queue, :enabled], false) + + if enabled do + Logger.info("Starting retry queue") + GenServer.start_link(__MODULE__, %{delivered: 0, dropped: 0}, name: __MODULE__) + else + Logger.info("Retry queue disabled") + :ignore + end end def enqueue(data, transport, retries \\ 0) do @@ -38,7 +45,7 @@ defmodule Pleroma.Web.Federator.RetryQueue do Process.send_after( __MODULE__, {:send, data, transport, retries}, - growth_function(retries) + timeout ) {:noreply, state} @@ -54,7 +61,7 @@ defmodule Pleroma.Web.Federator.RetryQueue do {:ok, _} -> {:noreply, %{state | delivered: delivery_count + 1}} - {:error, reason} -> + {:error, _reason} -> enqueue(data, transport, retries) {:noreply, state} end diff --git a/lib/pleroma/web/gettext.ex b/lib/pleroma/web/gettext.ex index 501545581..f40fd04c0 100644 --- a/lib/pleroma/web/gettext.ex +++ b/lib/pleroma/web/gettext.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.Gettext do @moduledoc """ A module providing Internationalization with a gettext-based API. diff --git a/lib/pleroma/web/http_signatures/http_signatures.ex b/lib/pleroma/web/http_signatures/http_signatures.ex index 5e42a871b..0e4f8f14b 100644 --- a/lib/pleroma/web/http_signatures/http_signatures.ex +++ b/lib/pleroma/web/http_signatures/http_signatures.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + # https://tools.ietf.org/html/draft-cavage-http-signatures-08 defmodule Pleroma.Web.HTTPSignatures do alias Pleroma.User @@ -65,7 +69,7 @@ defmodule Pleroma.Web.HTTPSignatures do end def sign(user, headers) do - with {:ok, %{info: %{"keys" => keys}}} <- Pleroma.Web.WebFinger.ensure_keys_present(user), + with {:ok, %{info: %{keys: keys}}} <- Pleroma.Web.WebFinger.ensure_keys_present(user), {:ok, private_key, _} = Pleroma.Web.Salmon.keys_from_pem(keys) do sigstring = build_signing_string(headers, Map.keys(headers)) diff --git a/lib/pleroma/web/mastodon_api/mastodon_api_controller.ex b/lib/pleroma/web/mastodon_api/mastodon_api_controller.ex index aa7e9418e..22715bb76 100644 --- a/lib/pleroma/web/mastodon_api/mastodon_api_controller.ex +++ b/lib/pleroma/web/mastodon_api/mastodon_api_controller.ex @@ -1,14 +1,27 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do use Pleroma.Web, :controller alias Pleroma.{Repo, Object, Activity, User, Notification, Stats} alias Pleroma.Web - alias Pleroma.Web.MastodonAPI.{StatusView, AccountView, MastodonView, ListView, FilterView} + + alias Pleroma.Web.MastodonAPI.{ + StatusView, + AccountView, + MastodonView, + ListView, + FilterView, + PushSubscriptionView + } + alias Pleroma.Web.ActivityPub.ActivityPub alias Pleroma.Web.ActivityPub.Utils alias Pleroma.Web.CommonAPI alias Pleroma.Web.OAuth.{Authorization, Token, App} alias Pleroma.Web.MediaProxy - alias Comeonin.Pbkdf2 + import Ecto.Query require Logger @@ -32,75 +45,55 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do end end - def update_credentials(%{assigns: %{user: user}} = conn, params) do - original_user = user - - avatar_upload_limit = - Application.get_env(:pleroma, :instance) - |> Keyword.fetch(:avatar_upload_limit) - - banner_upload_limit = - Application.get_env(:pleroma, :instance) - |> Keyword.fetch(:banner_upload_limit) - - params = - if bio = params["note"] do - Map.put(params, "bio", bio) - else - params + defp add_if_present( + map, + params, + params_field, + map_field, + value_function \\ fn x -> {:ok, x} end + ) do + if Map.has_key?(params, params_field) do + case value_function.(params[params_field]) do + {:ok, new_value} -> Map.put(map, map_field, new_value) + :error -> map end + else + map + end + end - params = - if name = params["display_name"] do - Map.put(params, "name", name) - else - params - end + def update_credentials(%{assigns: %{user: user}} = conn, params) do + original_user = user - user = - if avatar = params["avatar"] do - with %Plug.Upload{} <- avatar, - {:ok, object} <- ActivityPub.upload(avatar, avatar_upload_limit), - change = Ecto.Changeset.change(user, %{avatar: object.data}), - {:ok, user} = User.update_and_set_cache(change) do - user + user_params = + %{} + |> add_if_present(params, "display_name", :name) + |> add_if_present(params, "note", :bio, fn value -> {:ok, User.parse_bio(value)} end) + |> add_if_present(params, "avatar", :avatar, fn value -> + with %Plug.Upload{} <- value, + {:ok, object} <- ActivityPub.upload(value, type: :avatar) do + {:ok, object.data} else - _e -> user + _ -> :error end - else - user - end + end) - user = - if banner = params["header"] do - with %Plug.Upload{} <- banner, - {:ok, object} <- ActivityPub.upload(banner, banner_upload_limit), - new_info <- Map.put(user.info, "banner", object.data), - change <- User.info_changeset(user, %{info: new_info}), - {:ok, user} <- User.update_and_set_cache(change) do - user + info_params = + %{} + |> add_if_present(params, "locked", :locked, fn value -> {:ok, value == "true"} end) + |> add_if_present(params, "header", :banner, fn value -> + with %Plug.Upload{} <- value, + {:ok, object} <- ActivityPub.upload(value, type: :banner) do + {:ok, object.data} else - _e -> user + _ -> :error end - else - user - end + end) - user = - if locked = params["locked"] do - with locked <- locked == "true", - new_info <- Map.put(user.info, "locked", locked), - change <- User.info_changeset(user, %{info: new_info}), - {:ok, user} <- User.update_and_set_cache(change) do - user - else - _e -> user - end - else - user - end + info_cng = User.Info.mastodon_profile_update(user.info, info_params) - with changeset <- User.update_changeset(user, params), + with changeset <- User.update_changeset(user, user_params), + changeset <- Ecto.Changeset.put_embed(changeset, :info, info_cng), {:ok, user} <- User.update_and_set_cache(changeset) do if original_user != user do CommonAPI.update(user) @@ -121,7 +114,8 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do end def user(%{assigns: %{user: for_user}} = conn, %{"id" => id}) do - with %User{} = user <- Repo.get(User, id) do + with %User{} = user <- Repo.get(User, id), + true <- User.auth_active?(user) || user.id == for_user.id || User.superuser?(for_user) do account = AccountView.render("account.json", %{user: user, for: for_user}) json(conn, account) else @@ -237,7 +231,8 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do conn |> add_link_headers(:home_timeline, activities) - |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity}) + |> put_view(StatusView) + |> render("index.json", %{activities: activities, for: user, as: :activity}) end def public_timeline(%{assigns: %{user: user}} = conn, params) do @@ -255,7 +250,8 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do conn |> add_link_headers(:public_timeline, activities, false, %{"local" => local_only}) - |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity}) + |> put_view(StatusView) + |> render("index.json", %{activities: activities, for: user, as: :activity}) end def user_statuses(%{assigns: %{user: reading_user}} = conn, params) do @@ -270,7 +266,8 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do conn |> add_link_headers(:user_statuses, activities, params["id"]) - |> render(StatusView, "index.json", %{ + |> put_view(StatusView) + |> render("index.json", %{ activities: activities, for: reading_user, as: :activity @@ -289,13 +286,16 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do conn |> add_link_headers(:dm_timeline, activities) - |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity}) + |> put_view(StatusView) + |> render("index.json", %{activities: activities, for: user, as: :activity}) end def get_status(%{assigns: %{user: user}} = conn, %{"id" => id}) do with %Activity{} = activity <- Repo.get(Activity, id), true <- ActivityPub.visible_for_user?(activity, user) do - try_render(conn, StatusView, "status.json", %{activity: activity, for: user}) + conn + |> put_view(StatusView) + |> try_render("status.json", %{activity: activity, for: user}) end end @@ -358,7 +358,9 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do {:ok, activity} = Cachex.fetch!(:idempotency_cache, idempotency_key, fn _ -> CommonAPI.post(user, params) end) - try_render(conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity}) + conn + |> put_view(StatusView) + |> try_render("status.json", %{activity: activity, for: user, as: :activity}) end def delete_status(%{assigns: %{user: user}} = conn, %{"id" => id}) do @@ -374,28 +376,36 @@ 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) do - try_render(conn, StatusView, "status.json", %{activity: announce, for: user, as: :activity}) + conn + |> put_view(StatusView) + |> try_render("status.json", %{activity: announce, for: user, as: :activity}) end end 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_activity_by_object_ap_id(id) do - try_render(conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity}) + conn + |> put_view(StatusView) + |> try_render("status.json", %{activity: activity, for: user, as: :activity}) end end def fav_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do with {:ok, _fav, %{data: %{"id" => id}}} <- CommonAPI.favorite(ap_id_or_id, user), %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do - try_render(conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity}) + conn + |> put_view(StatusView) + |> try_render("status.json", %{activity: activity, for: user, as: :activity}) end end def unfav_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do with {:ok, _, _, %{data: %{"id" => id}}} <- CommonAPI.unfavorite(ap_id_or_id, user), %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do - try_render(conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity}) + conn + |> put_view(StatusView) + |> try_render("status.json", %{activity: activity, for: user, as: :activity}) end end @@ -444,49 +454,46 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do id = List.wrap(id) q = from(u in User, where: u.id in ^id) targets = Repo.all(q) - render(conn, AccountView, "relationships.json", %{user: user, targets: targets}) - end - # Instead of returning a 400 when no "id" params is present, Mastodon returns an empty array. - def relationships(%{assigns: %{user: user}} = conn, _) do conn - |> json([]) + |> put_view(AccountView) + |> render("relationships.json", %{user: user, targets: targets}) end - def update_media(%{assigns: %{user: _}} = conn, data) do + # Instead of returning a 400 when no "id" params is present, Mastodon returns an empty array. + def relationships(%{assigns: %{user: _user}} = conn, _), do: json(conn, []) + + def update_media(%{assigns: %{user: user}} = conn, data) do with %Object{} = object <- Repo.get(Object, data["id"]), + true <- Object.authorize_mutation(object, user), true <- is_binary(data["description"]), description <- data["description"] do new_data = %{object.data | "name" => description} - change = Object.change(object, %{data: new_data}) - {:ok, _} = Repo.update(change) + {:ok, _} = + object + |> Object.change(%{data: new_data}) + |> Repo.update() - data = - new_data - |> Map.put("id", object.id) + attachment_data = Map.put(new_data, "id", object.id) - render(conn, StatusView, "attachment.json", %{attachment: data}) + conn + |> put_view(StatusView) + |> render("attachment.json", %{attachment: attachment_data}) end end - def upload(%{assigns: %{user: _}} = conn, %{"file" => file} = data) do - with {:ok, object} <- ActivityPub.upload(file) do - objdata = - if Map.has_key?(data, "description") do - Map.put(object.data, "name", data["description"]) - else - object.data - end - - change = Object.change(object, %{data: objdata}) - {:ok, object} = Repo.update(change) - - objdata = - objdata - |> Map.put("id", object.id) + def upload(%{assigns: %{user: user}} = conn, %{"file" => file} = data) do + with {:ok, object} <- + ActivityPub.upload(file, + actor: User.ap_id(user), + description: Map.get(data, "description") + ) do + attachment_data = Map.put(object.data, "id", object.id) - render(conn, StatusView, "attachment.json", %{attachment: objdata}) + conn + |> put_view(StatusView) + |> render("attachment.json", %{attachment: attachment_data}) end end @@ -494,7 +501,10 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do with %Activity{data: %{"object" => %{"likes" => likes}}} <- Repo.get(Activity, id) do q = from(u in User, where: u.ap_id in ^likes) users = Repo.all(q) - render(conn, AccountView, "accounts.json", %{users: users, as: :user}) + + conn + |> put_view(AccountView) + |> render(AccountView, "accounts.json", %{users: users, as: :user}) else _ -> json(conn, []) end @@ -504,7 +514,10 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do with %Activity{data: %{"object" => %{"announcements" => announces}}} <- Repo.get(Activity, id) do q = from(u in User, where: u.ap_id in ^announces) users = Repo.all(q) - render(conn, AccountView, "accounts.json", %{users: users, as: :user}) + + conn + |> put_view(AccountView) + |> render("accounts.json", %{users: users, as: :user}) else _ -> json(conn, []) end @@ -526,27 +539,47 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do conn |> add_link_headers(:hashtag_timeline, activities, params["tag"], %{"local" => local_only}) - |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity}) + |> put_view(StatusView) + |> render("index.json", %{activities: activities, for: user, as: :activity}) end - # TODO: Pagination - def followers(conn, %{"id" => id}) do + def followers(%{assigns: %{user: for_user}} = conn, %{"id" => id}) do with %User{} = user <- Repo.get(User, id), {:ok, followers} <- User.get_followers(user) do - render(conn, AccountView, "accounts.json", %{users: followers, as: :user}) + followers = + cond do + for_user && user.id == for_user.id -> followers + user.info.hide_network -> [] + true -> followers + end + + conn + |> put_view(AccountView) + |> render("accounts.json", %{users: followers, as: :user}) end end - def following(conn, %{"id" => id}) do + def following(%{assigns: %{user: for_user}} = conn, %{"id" => id}) do with %User{} = user <- Repo.get(User, id), {:ok, followers} <- User.get_friends(user) do - render(conn, AccountView, "accounts.json", %{users: followers, as: :user}) + followers = + cond do + for_user && user.id == for_user.id -> followers + user.info.hide_network -> [] + true -> followers + end + + conn + |> put_view(AccountView) + |> render("accounts.json", %{users: followers, as: :user}) end end def follow_requests(%{assigns: %{user: followed}} = conn, _params) do with {:ok, follow_requests} <- User.get_follow_requests(followed) do - render(conn, AccountView, "accounts.json", %{users: follow_requests, as: :user}) + conn + |> put_view(AccountView) + |> render("accounts.json", %{users: follow_requests, as: :user}) end end @@ -562,7 +595,9 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do object: follow_activity.data["id"], type: "Accept" }) do - render(conn, AccountView, "relationship.json", %{user: followed, target: follower}) + conn + |> put_view(AccountView) + |> render("relationship.json", %{user: followed, target: follower}) else {:error, message} -> conn @@ -582,7 +617,9 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do object: follow_activity.data["id"], type: "Reject" }) do - render(conn, AccountView, "relationship.json", %{user: followed, target: follower}) + conn + |> put_view(AccountView) + |> render("relationship.json", %{user: followed, target: follower}) else {:error, message} -> conn @@ -601,7 +638,9 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do follower, followed ) do - render(conn, AccountView, "relationship.json", %{user: follower, target: followed}) + conn + |> put_view(AccountView) + |> render("relationship.json", %{user: follower, target: followed}) else {:error, message} -> conn @@ -614,7 +653,9 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do with %User{} = followed <- Repo.get_by(User, nickname: uri), {:ok, follower} <- User.maybe_direct_follow(follower, followed), {:ok, _activity} <- ActivityPub.follow(follower, followed) do - render(conn, AccountView, "account.json", %{user: followed, for: follower}) + conn + |> put_view(AccountView) + |> render("account.json", %{user: followed, for: follower}) else {:error, message} -> conn @@ -627,7 +668,9 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do with %User{} = followed <- Repo.get(User, id), {:ok, _activity} <- ActivityPub.unfollow(follower, followed), {:ok, follower, _} <- User.unfollow(follower, followed) do - render(conn, AccountView, "relationship.json", %{user: follower, target: followed}) + conn + |> put_view(AccountView) + |> render("relationship.json", %{user: follower, target: followed}) end end @@ -635,7 +678,9 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do with %User{} = blocked <- Repo.get(User, id), {:ok, blocker} <- User.block(blocker, blocked), {:ok, _activity} <- ActivityPub.block(blocker, blocked) do - render(conn, AccountView, "relationship.json", %{user: blocker, target: blocked}) + conn + |> put_view(AccountView) + |> render("relationship.json", %{user: blocker, target: blocked}) else {:error, message} -> conn @@ -648,7 +693,9 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do with %User{} = blocked <- Repo.get(User, id), {:ok, blocker} <- User.unblock(blocker, blocked), {:ok, _activity} <- ActivityPub.unblock(blocker, blocked) do - render(conn, AccountView, "relationship.json", %{user: blocker, target: blocked}) + conn + |> put_view(AccountView) + |> render("relationship.json", %{user: blocker, target: blocked}) else {:error, message} -> conn @@ -659,7 +706,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do # TODO: Use proper query def blocks(%{assigns: %{user: user}} = conn, _) do - with blocked_users <- user.info["blocks"] || [], + with blocked_users <- user.info.blocks || [], accounts <- Enum.map(blocked_users, fn ap_id -> User.get_cached_by_ap_id(ap_id) end) do res = AccountView.render("accounts.json", users: accounts, for: user, as: :user) json(conn, res) @@ -667,7 +714,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do end def domain_blocks(%{assigns: %{user: %{info: info}}} = conn, _) do - json(conn, info["domain_blocks"] || []) + json(conn, info.domain_blocks || []) end def block_domain(%{assigns: %{user: blocker}} = conn, %{"domain" => domain}) do @@ -773,7 +820,8 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do |> Enum.reverse() conn - |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity}) + |> put_view(StatusView) + |> render("index.json", %{activities: activities, for: user, as: :activity}) end def get_lists(%{assigns: %{user: user}} = conn, opts) do @@ -841,7 +889,9 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do def list_accounts(%{assigns: %{user: user}} = conn, %{"id" => id}) do with %Pleroma.List{} = list <- Pleroma.List.get(id, user), {:ok, users} = Pleroma.List.get_following(list) do - render(conn, AccountView, "accounts.json", %{users: users, as: :user}) + conn + |> put_view(AccountView) + |> render("accounts.json", %{users: users, as: :user}) end end @@ -857,7 +907,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do end def list_timeline(%{assigns: %{user: user}} = conn, %{"list_id" => id} = params) do - with %Pleroma.List{title: title, following: following} <- Pleroma.List.get(id, user) do + with %Pleroma.List{title: _title, following: following} <- Pleroma.List.get(id, user) do params = params |> Map.put("type", "Create") @@ -874,7 +924,8 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do |> Enum.reverse() conn - |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity}) + |> put_view(StatusView) + |> render("index.json", %{activities: activities, for: user, as: :activity}) else _e -> conn @@ -915,11 +966,11 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do max_toot_chars: limit }, rights: %{ - delete_others_notice: !!user.info["is_moderator"] + delete_others_notice: !!user.info.is_moderator }, compose: %{ me: "#{user.id}", - default_privacy: user.info["default_scope"] || "public", + default_privacy: user.info.default_scope, default_sensitive: false }, media_attachments: %{ @@ -939,7 +990,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do ] }, settings: - Map.get(user.info, "settings") || + user.info.settings || %{ onboarded: true, home: %{ @@ -978,7 +1029,8 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do conn |> put_layout(false) - |> render(MastodonView, "index.html", %{initial_state: initial_state}) + |> put_view(MastodonView) + |> render("index.html", %{initial_state: initial_state}) else conn |> redirect(to: "/web/login") @@ -986,15 +1038,17 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do end def put_settings(%{assigns: %{user: user}} = conn, %{"data" => settings} = _params) do - with new_info <- Map.put(user.info, "settings", settings), - change <- User.info_changeset(user, %{info: new_info}), - {:ok, _user} <- User.update_and_set_cache(change) do - conn - |> json(%{}) + info_cng = User.Info.mastodon_settings_update(user.info, settings) + + with changeset <- Ecto.Changeset.change(user), + changeset <- Ecto.Changeset.put_embed(changeset, :info, info_cng), + {:ok, _user} <- User.update_and_set_cache(changeset) do + json(conn, %{}) else e -> conn - |> json(%{error: inspect(e)}) + |> put_resp_content_type("application/json") + |> send_resp(500, Jason.encode!(%{"error" => inspect(e)})) end end @@ -1049,7 +1103,9 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do Logger.debug("Unimplemented, returning unmodified relationship") with %User{} = target <- Repo.get(User, id) do - render(conn, AccountView, "relationship.json", %{user: user, target: target}) + conn + |> put_view(AccountView) + |> render("relationship.json", %{user: user, target: target}) end end @@ -1065,52 +1121,37 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do def render_notification(user, %{id: id, activity: activity, inserted_at: created_at} = _params) do actor = User.get_cached_by_ap_id(activity.data["actor"]) + parent_activity = Activity.get_create_activity_by_object_ap_id(activity.data["object"]) + mastodon_type = Activity.mastodon_notification_type(activity) - created_at = - NaiveDateTime.to_iso8601(created_at) - |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false) - - id = id |> to_string + response = %{ + id: to_string(id), + type: mastodon_type, + created_at: CommonAPI.Utils.to_masto_date(created_at), + account: AccountView.render("account.json", %{user: actor, for: user}) + } - case activity.data["type"] do - "Create" -> - %{ - id: id, - type: "mention", - created_at: created_at, - account: AccountView.render("account.json", %{user: actor, for: user}), + case mastodon_type do + "mention" -> + response + |> Map.merge(%{ status: StatusView.render("status.json", %{activity: activity, for: user}) - } - - "Like" -> - liked_activity = Activity.get_create_activity_by_object_ap_id(activity.data["object"]) + }) - %{ - id: id, - type: "favourite", - created_at: created_at, - account: AccountView.render("account.json", %{user: actor, for: user}), - status: StatusView.render("status.json", %{activity: liked_activity, for: user}) - } - - "Announce" -> - announced_activity = Activity.get_create_activity_by_object_ap_id(activity.data["object"]) + "favourite" -> + response + |> Map.merge(%{ + status: StatusView.render("status.json", %{activity: parent_activity, for: user}) + }) - %{ - id: id, - type: "reblog", - created_at: created_at, - account: AccountView.render("account.json", %{user: actor, for: user}), - status: StatusView.render("status.json", %{activity: announced_activity, for: user}) - } + "reblog" -> + response + |> Map.merge(%{ + status: StatusView.render("status.json", %{activity: parent_activity, for: user}) + }) - "Follow" -> - %{ - id: id, - type: "follow", - created_at: created_at, - account: AccountView.render("account.json", %{user: actor, for: user}) - } + "follow" -> + response _ -> nil @@ -1176,6 +1217,37 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do json(conn, %{}) end + def create_push_subscription(%{assigns: %{user: user, token: token}} = conn, params) do + true = Pleroma.Web.Push.enabled() + Pleroma.Web.Push.Subscription.delete_if_exists(user, token) + {:ok, subscription} = Pleroma.Web.Push.Subscription.create(user, token, params) + view = PushSubscriptionView.render("push_subscription.json", subscription: subscription) + json(conn, view) + end + + def get_push_subscription(%{assigns: %{user: user, token: token}} = conn, _params) do + true = Pleroma.Web.Push.enabled() + subscription = Pleroma.Web.Push.Subscription.get(user, token) + view = PushSubscriptionView.render("push_subscription.json", subscription: subscription) + json(conn, view) + end + + def update_push_subscription( + %{assigns: %{user: user, token: token}} = conn, + params + ) do + true = Pleroma.Web.Push.enabled() + {:ok, subscription} = Pleroma.Web.Push.Subscription.update(user, token, params) + view = PushSubscriptionView.render("push_subscription.json", subscription: subscription) + json(conn, view) + end + + def delete_push_subscription(%{assigns: %{user: user, token: token}} = conn, _params) do + true = Pleroma.Web.Push.enabled() + {:ok, _response} = Pleroma.Web.Push.Subscription.delete(user, token) + json(conn, %{}) + end + def errors(conn, _) do conn |> put_status(500) @@ -1195,8 +1267,15 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do user = user.nickname url = String.replace(api, "{{host}}", host) |> String.replace("{{user}}", user) - with {:ok, %{status_code: 200, body: body}} <- - @httpoison.get(url, [], timeout: timeout, recv_timeout: timeout), + with {:ok, %{status: 200, body: body}} <- + @httpoison.get( + url, + [], + adapter: [ + timeout: timeout, + recv_timeout: timeout + ] + ), {:ok, data} <- Jason.decode(body) do data2 = Enum.slice(data, 0, limit) @@ -1227,9 +1306,9 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do end end - def try_render(conn, renderer, target, params) + def try_render(conn, target, params) when is_binary(target) do - res = render(conn, renderer, target, params) + res = render(conn, target, params) if res == nil do conn @@ -1240,7 +1319,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do end end - def try_render(conn, _, _, _) do + def try_render(conn, _, _) do conn |> put_status(501) |> json(%{error: "Can't display this activity"}) diff --git a/lib/pleroma/web/mastodon_api/mastodon_socket.ex b/lib/pleroma/web/mastodon_api/mastodon_socket.ex deleted file mode 100644 index f3c13d1aa..000000000 --- a/lib/pleroma/web/mastodon_api/mastodon_socket.ex +++ /dev/null @@ -1,80 +0,0 @@ -defmodule Pleroma.Web.MastodonAPI.MastodonSocket do - use Phoenix.Socket - - alias Pleroma.Web.OAuth.Token - alias Pleroma.{User, Repo} - - transport( - :streaming, - Phoenix.Transports.WebSocket.Raw, - # We never receive data. - timeout: :infinity - ) - - def connect(%{"access_token" => token} = params, socket) do - with %Token{user_id: user_id} <- Repo.get_by(Token, token: token), - %User{} = user <- Repo.get(User, user_id), - stream - when stream in [ - "public", - "public:local", - "public:media", - "public:local:media", - "user", - "direct", - "list", - "hashtag" - ] <- params["stream"] do - topic = - case stream do - "hashtag" -> "hashtag:#{params["tag"]}" - "list" -> "list:#{params["list"]}" - _ -> stream - end - - socket = - socket - |> assign(:topic, topic) - |> assign(:user, user) - - Pleroma.Web.Streamer.add_socket(topic, socket) - {:ok, socket} - else - _e -> :error - end - end - - def connect(%{"stream" => stream} = params, socket) - when stream in ["public", "public:local", "hashtag"] do - topic = - case stream do - "hashtag" -> "hashtag:#{params["tag"]}" - _ -> stream - end - - with socket = - socket - |> assign(:topic, topic) do - Pleroma.Web.Streamer.add_socket(topic, socket) - {:ok, socket} - else - _e -> :error - end - end - - def id(_), do: nil - - def handle(:text, message, _state) do - # | :ok - # | state - # | {:text, message} - # | {:text, message, state} - # | {:close, "Goodbye!"} - {:text, message} - end - - def handle(:closed, _, %{socket: socket}) do - topic = socket.assigns[:topic] - Pleroma.Web.Streamer.remove_socket(topic, socket) - end -end diff --git a/lib/pleroma/web/mastodon_api/views/account_view.ex b/lib/pleroma/web/mastodon_api/views/account_view.ex index b68845e16..aaaae2035 100644 --- a/lib/pleroma/web/mastodon_api/views/account_view.ex +++ b/lib/pleroma/web/mastodon_api/views/account_view.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.MastodonAPI.AccountView do use Pleroma.Web, :view alias Pleroma.User @@ -14,10 +18,10 @@ defmodule Pleroma.Web.MastodonAPI.AccountView do image = User.avatar_url(user) |> MediaProxy.url() header = User.banner_url(user) |> MediaProxy.url() user_info = User.user_info(user) - bot = (user.info["source_data"]["type"] || "Person") in ["Application", "Service"] + bot = (user.info.source_data["type"] || "Person") in ["Application", "Service"] emojis = - (user.info["source_data"]["tag"] || []) + (user.info.source_data["tag"] || []) |> Enum.filter(fn %{"type" => t} -> t == "Emoji" end) |> Enum.map(fn %{"icon" => %{"url" => url}, "name" => name} -> %{ @@ -29,7 +33,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountView do end) fields = - (user.info["source_data"]["attachment"] || []) + (user.info.source_data["attachment"] || []) |> Enum.filter(fn %{"type" => t} -> t == "PropertyValue" end) |> Enum.map(fn fields -> Map.take(fields, ["name", "value"]) end) @@ -58,6 +62,12 @@ defmodule Pleroma.Web.MastodonAPI.AccountView do note: "", privacy: user_info.default_scope, sensitive: false + }, + + # Pleroma extension + pleroma: %{ + confirmation_pending: user_info.confirmation_pending, + tags: user.tags } } end diff --git a/lib/pleroma/web/mastodon_api/views/filter_view.ex b/lib/pleroma/web/mastodon_api/views/filter_view.ex index 6bd687d46..ffbd830e1 100644 --- a/lib/pleroma/web/mastodon_api/views/filter_view.ex +++ b/lib/pleroma/web/mastodon_api/views/filter_view.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.MastodonAPI.FilterView do use Pleroma.Web, :view alias Pleroma.Web.MastodonAPI.FilterView diff --git a/lib/pleroma/web/mastodon_api/views/list_view.ex b/lib/pleroma/web/mastodon_api/views/list_view.ex index 1a1b7430b..dd0121f7a 100644 --- a/lib/pleroma/web/mastodon_api/views/list_view.ex +++ b/lib/pleroma/web/mastodon_api/views/list_view.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.MastodonAPI.ListView do use Pleroma.Web, :view alias Pleroma.Web.MastodonAPI.ListView diff --git a/lib/pleroma/web/mastodon_api/views/mastodon_view.ex b/lib/pleroma/web/mastodon_api/views/mastodon_view.ex index 370fad374..a3adabc50 100644 --- a/lib/pleroma/web/mastodon_api/views/mastodon_view.ex +++ b/lib/pleroma/web/mastodon_api/views/mastodon_view.ex @@ -1,5 +1,8 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.MastodonAPI.MastodonView do use Pleroma.Web, :view import Phoenix.HTML - import Phoenix.HTML.Form end diff --git a/lib/pleroma/web/mastodon_api/views/push_subscription_view.ex b/lib/pleroma/web/mastodon_api/views/push_subscription_view.ex new file mode 100644 index 000000000..7970bcd47 --- /dev/null +++ b/lib/pleroma/web/mastodon_api/views/push_subscription_view.ex @@ -0,0 +1,20 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.Web.MastodonAPI.PushSubscriptionView do + use Pleroma.Web, :view + + def render("push_subscription.json", %{subscription: subscription}) do + %{ + id: to_string(subscription.id), + endpoint: subscription.endpoint, + alerts: Map.get(subscription.data, "alerts"), + server_key: server_key() + } + end + + defp server_key do + Keyword.get(Application.get_env(:web_push_encryption, :vapid_details), :public_key) + 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 2d9a915f0..4d4681da8 100644 --- a/lib/pleroma/web/mastodon_api/views/status_view.ex +++ b/lib/pleroma/web/mastodon_api/views/status_view.ex @@ -1,18 +1,25 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.MastodonAPI.StatusView do use Pleroma.Web, :view - alias Pleroma.Web.MastodonAPI.{AccountView, StatusView} - alias Pleroma.{User, Activity} + + alias Pleroma.Activity + alias Pleroma.HTML + alias Pleroma.Repo + alias Pleroma.User alias Pleroma.Web.CommonAPI.Utils alias Pleroma.Web.MediaProxy - alias Pleroma.Repo - alias Pleroma.HTML + alias Pleroma.Web.MastodonAPI.AccountView + alias Pleroma.Web.MastodonAPI.StatusView # TODO: Add cached version. defp get_replied_to_activities(activities) do activities |> Enum.map(fn - %{data: %{"type" => "Create", "object" => %{"inReplyTo" => inReplyTo}}} -> - inReplyTo != "" && inReplyTo + %{data: %{"type" => "Create", "object" => %{"inReplyTo" => in_reply_to}}} -> + in_reply_to != "" && in_reply_to _ -> nil @@ -28,8 +35,8 @@ defmodule Pleroma.Web.MastodonAPI.StatusView do def render("index.json", opts) do replied_to_activities = get_replied_to_activities(opts.activities) - render_many( - opts.activities, + opts.activities + |> render_many( StatusView, "status.json", Map.put(opts, :replied_to_activities, replied_to_activities) @@ -72,9 +79,9 @@ defmodule Pleroma.Web.MastodonAPI.StatusView do sensitive: false, spoiler_text: "", visibility: "public", - media_attachments: [], + media_attachments: reblogged[:media_attachments] || [], mentions: mentions, - tags: [], + tags: reblogged[:tags] || [], application: %{ name: "Web", website: nil @@ -103,7 +110,6 @@ defmodule Pleroma.Web.MastodonAPI.StatusView do favorited = opts[:for] && opts[:for].ap_id in (object["likes"] || []) attachment_data = object["attachment"] || [] - attachment_data = attachment_data ++ if object["type"] == "Video", do: [object], else: [] attachments = render_many(attachment_data, StatusView, "attachment.json", as: :attachment) created_at = Utils.to_masto_date(object["published"]) @@ -111,20 +117,9 @@ defmodule Pleroma.Web.MastodonAPI.StatusView do reply_to = get_reply_to(activity, opts) reply_to_user = reply_to && User.get_cached_by_ap_id(reply_to.data["actor"]) - emojis = - (activity.data["object"]["emoji"] || []) - |> Enum.map(fn {name, url} -> - name = HTML.strip_tags(name) - - url = - HTML.strip_tags(url) - |> MediaProxy.url() - - %{shortcode: name, url: url, static_url: url, visible_in_picker: false} - end) - content = - render_content(object) + object + |> render_content() |> HTML.filter_tags(User.html_filter_policy(opts[:for])) %{ @@ -140,22 +135,21 @@ defmodule Pleroma.Web.MastodonAPI.StatusView do reblogs_count: announcement_count, replies_count: 0, favourites_count: like_count, - reblogged: !!repeated, - favourited: !!favorited, + reblogged: present?(repeated), + favourited: present?(favorited), muted: false, sensitive: sensitive, spoiler_text: object["summary"] || "", visibility: get_visibility(object), media_attachments: attachments |> Enum.take(4), mentions: mentions, - # fix, - tags: [], + tags: build_tags(tags), application: %{ name: "Web", website: nil }, language: nil, - emojis: emojis + emojis: build_emojis(activity.data["object"]["emoji"]) } end @@ -224,30 +218,77 @@ defmodule Pleroma.Web.MastodonAPI.StatusView do end def render_content(%{"type" => "Video"} = object) do - name = object["name"] + with name when not is_nil(name) and name != "" <- object["name"] do + "<p><a href=\"#{object["id"]}\">#{name}</a></p>#{object["content"]}" + else + _ -> object["content"] || "" + end + end - content = - if !!name and name != "" do - "<p><a href=\"#{object["id"]}\">#{name}</a></p>#{object["content"]}" - else - object["content"] || "" - end + def render_content(%{"type" => object_type} = object) + when object_type in ["Article", "Page"] do + with summary when not is_nil(summary) and summary != "" <- object["name"], + url when is_bitstring(url) <- object["url"] do + "<p><a href=\"#{url}\">#{summary}</a></p>#{object["content"]}" + else + _ -> object["content"] || "" + end + end - content + def render_content(object), do: object["content"] || "" + + @doc """ + Builds a dictionary tags. + + ## Examples + + iex> Pleroma.Web.MastodonAPI.StatusView.build_tags(["fediverse", "nextcloud"]) + [{"name": "fediverse", "url": "/tag/fediverse"}, + {"name": "nextcloud", "url": "/tag/nextcloud"}] + + """ + @spec build_tags(list(any())) :: list(map()) + def build_tags(object_tags) when is_list(object_tags) do + object_tags = for tag when is_binary(tag) <- object_tags, do: tag + + Enum.reduce(object_tags, [], fn tag, tags -> + tags ++ [%{name: tag, url: "/tag/#{tag}"}] + end) end - def render_content(%{"type" => object_type} = object) when object_type in ["Article", "Page"] do - summary = object["name"] + def build_tags(_), do: [] - content = - if !!summary and summary != "" and is_bitstring(object["url"]) do - "<p><a href=\"#{object["url"]}\">#{summary}</a></p>#{object["content"]}" - else - object["content"] || "" - end + @doc """ + Builds list emojis. + + Arguments: `nil` or list tuple of name and url. - content + Returns list emojis. + + ## Examples + + iex> Pleroma.Web.MastodonAPI.StatusView.build_emojis([{"2hu", "corndog.png"}]) + [%{shortcode: "2hu", static_url: "corndog.png", url: "corndog.png", visible_in_picker: false}] + + """ + @spec build_emojis(nil | list(tuple())) :: list(map()) + def build_emojis(nil), do: [] + + def build_emojis(emojis) do + emojis + |> Enum.map(fn {name, url} -> + name = HTML.strip_tags(name) + + url = + url + |> HTML.strip_tags() + |> MediaProxy.url() + + %{shortcode: name, url: url, static_url: url, visible_in_picker: false} + end) end - def render_content(object), do: object["content"] || "" + defp present?(nil), do: false + defp present?(false), do: false + defp present?(_), do: true end diff --git a/lib/pleroma/web/mastodon_api/websocket_handler.ex b/lib/pleroma/web/mastodon_api/websocket_handler.ex new file mode 100644 index 000000000..7b90649ad --- /dev/null +++ b/lib/pleroma/web/mastodon_api/websocket_handler.ex @@ -0,0 +1,124 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.Web.MastodonAPI.WebsocketHandler do + require Logger + + alias Pleroma.Web.OAuth.Token + alias Pleroma.{User, Repo} + + @behaviour :cowboy_websocket_handler + + @streams [ + "public", + "public:local", + "public:media", + "public:local:media", + "user", + "direct", + "list", + "hashtag" + ] + @anonymous_streams ["public", "public:local", "hashtag"] + + # Handled by periodic keepalive in Pleroma.Web.Streamer. + @timeout :infinity + + def init(_type, _req, _opts) do + {:upgrade, :protocol, :cowboy_websocket} + end + + def websocket_init(_type, req, _opts) do + with {qs, req} <- :cowboy_req.qs(req), + params <- :cow_qs.parse_qs(qs), + access_token <- List.keyfind(params, "access_token", 0), + {_, stream} <- List.keyfind(params, "stream", 0), + {:ok, user} <- allow_request(stream, access_token), + topic when is_binary(topic) <- expand_topic(stream, params) do + send(self(), :subscribe) + {:ok, req, %{user: user, topic: topic}, @timeout} + else + {:error, code} -> + Logger.debug("#{__MODULE__} denied connection: #{inspect(code)} - #{inspect(req)}") + {:ok, req} = :cowboy_req.reply(code, req) + {:shutdown, req} + + error -> + Logger.debug("#{__MODULE__} denied connection: #{inspect(error)} - #{inspect(req)}") + {:shutdown, req} + end + end + + # We never receive messages. + def websocket_handle(_frame, req, state) do + {:ok, req, state} + end + + def websocket_info(:subscribe, req, state) do + Logger.debug( + "#{__MODULE__} accepted websocket connection for user #{ + (state.user || %{id: "anonymous"}).id + }, topic #{state.topic}" + ) + + Pleroma.Web.Streamer.add_socket(state.topic, streamer_socket(state)) + {:ok, req, state} + end + + def websocket_info({:text, message}, req, state) do + {:reply, {:text, message}, req, state} + end + + def websocket_terminate(reason, _req, state) do + Logger.debug( + "#{__MODULE__} terminating websocket connection for user #{ + (state.user || %{id: "anonymous"}).id + }, topic #{state.topic || "?"}: #{inspect(reason)}" + ) + + Pleroma.Web.Streamer.remove_socket(state.topic, streamer_socket(state)) + :ok + end + + # Public streams without authentication. + defp allow_request(stream, nil) when stream in @anonymous_streams do + {:ok, nil} + end + + # Authenticated streams. + defp allow_request(stream, {"access_token", access_token}) when stream in @streams do + with %Token{user_id: user_id} <- Repo.get_by(Token, token: access_token), + user = %User{} <- Repo.get(User, user_id) do + {:ok, user} + else + _ -> {:error, 403} + end + end + + # Not authenticated. + defp allow_request(stream, _) when stream in @streams, do: {:error, 403} + + # No matching stream. + defp allow_request(_, _), do: {:error, 404} + + defp expand_topic("hashtag", params) do + case List.keyfind(params, "tag", 0) do + {_, tag} -> "hashtag:#{tag}" + _ -> nil + end + end + + defp expand_topic("list", params) do + case List.keyfind(params, "list", 0) do + {_, list} -> "list:#{list}" + _ -> nil + end + end + + defp expand_topic(topic, _), do: topic + + defp streamer_socket(state) do + %{transport_pid: self(), assigns: state} + end +end diff --git a/lib/pleroma/web/media_proxy/controller.ex b/lib/pleroma/web/media_proxy/controller.ex index bb257c262..8c82b4176 100644 --- a/lib/pleroma/web/media_proxy/controller.ex +++ b/lib/pleroma/web/media_proxy/controller.ex @@ -1,135 +1,43 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.MediaProxy.MediaProxyController do use Pleroma.Web, :controller - require Logger - - @httpoison Application.get_env(:pleroma, :httpoison) - - @max_body_length 25 * 1_048_576 + alias Pleroma.{Web.MediaProxy, ReverseProxy} - @cache_control %{ - default: "public, max-age=1209600", - error: "public, must-revalidate, max-age=160" - } + @default_proxy_opts [max_body_length: 25 * 1_048_576, http: [follow_redirect: true]] - # Content-types that will not be returned as content-disposition attachments - # Override with :media_proxy, :safe_content_types in the configuration - @safe_content_types [ - "image/gif", - "image/jpeg", - "image/jpg", - "image/png", - "image/svg+xml", - "audio/mpeg", - "audio/mp3", - "video/webm", - "video/mp4" - ] - - def remote(conn, params = %{"sig" => sig, "url" => url}) do - config = Application.get_env(:pleroma, :media_proxy, []) - - with true <- Keyword.get(config, :enabled, false), - {:ok, url} <- Pleroma.Web.MediaProxy.decode_url(sig, url), - filename <- Path.basename(URI.parse(url).path), - true <- - if(Map.get(params, "filename"), - do: filename == Path.basename(conn.request_path), - else: true - ), - {:ok, content_type, body} <- proxy_request(url), - safe_content_type <- - Enum.member?( - Keyword.get(config, :safe_content_types, @safe_content_types), - content_type - ) do - conn - |> put_resp_content_type(content_type) - |> set_cache_header(:default) - |> put_resp_header( - "content-security-policy", - "default-src 'none'; style-src 'unsafe-inline'; media-src data:; img-src 'self' data:" - ) - |> put_resp_header("x-xss-protection", "1; mode=block") - |> put_resp_header("x-content-type-options", "nosniff") - |> put_attachement_header(safe_content_type, filename) - |> send_resp(200, body) + def remote(conn, params = %{"sig" => sig64, "url" => url64}) do + with config <- Pleroma.Config.get([:media_proxy], []), + true <- Keyword.get(config, :enabled, false), + {:ok, url} <- MediaProxy.decode_url(sig64, url64), + :ok <- filename_matches(Map.has_key?(params, "filename"), conn.request_path, url) do + ReverseProxy.call(conn, url, Keyword.get(config, :proxy_opts, @default_proxy_opts)) else false -> - send_error(conn, 404) + send_resp(conn, 404, Plug.Conn.Status.reason_phrase(404)) {:error, :invalid_signature} -> - send_error(conn, 403) + send_resp(conn, 403, Plug.Conn.Status.reason_phrase(403)) - {:error, {:http, _, url}} -> - redirect_or_error(conn, url, Keyword.get(config, :redirect_on_failure, true)) + {:wrong_filename, filename} -> + redirect(conn, external: MediaProxy.build_url(sig64, url64, filename)) end end - defp proxy_request(link) do - headers = [ - {"user-agent", - "Pleroma/MediaProxy; #{Pleroma.Web.base_url()} <#{ - Application.get_env(:pleroma, :instance)[:email] - }>"} - ] + def filename_matches(has_filename, path, url) do + filename = + url + |> MediaProxy.filename() + |> URI.decode() - options = - @httpoison.process_request_options([:insecure, {:follow_redirect, true}]) ++ - [{:pool, :default}] + path = URI.decode(path) - with {:ok, 200, headers, client} <- :hackney.request(:get, link, headers, "", options), - headers = Enum.into(headers, Map.new()), - {:ok, body} <- proxy_request_body(client), - content_type <- proxy_request_content_type(headers, body) do - {:ok, content_type, body} + if has_filename && filename && Path.basename(path) != filename do + {:wrong_filename, filename} else - {:ok, status, _, _} -> - Logger.warn("MediaProxy: request failed, status #{status}, link: #{link}") - {:error, {:http, :bad_status, link}} - - {:error, error} -> - Logger.warn("MediaProxy: request failed, error #{inspect(error)}, link: #{link}") - {:error, {:http, error, link}} - end - end - - defp set_cache_header(conn, key) do - Plug.Conn.put_resp_header(conn, "cache-control", @cache_control[key]) - end - - defp redirect_or_error(conn, url, true), do: redirect(conn, external: url) - defp redirect_or_error(conn, url, _), do: send_error(conn, 502, "Media proxy error: " <> url) - - defp send_error(conn, code, body \\ "") do - conn - |> set_cache_header(:error) - |> send_resp(code, body) - end - - defp proxy_request_body(client), do: proxy_request_body(client, <<>>) - - defp proxy_request_body(client, body) when byte_size(body) < @max_body_length do - case :hackney.stream_body(client) do - {:ok, data} -> proxy_request_body(client, <<body::binary, data::binary>>) - :done -> {:ok, body} - {:error, reason} -> {:error, reason} + :ok end end - - defp proxy_request_body(client, _) do - :hackney.close(client) - {:error, :body_too_large} - end - - # TODO: the body is passed here as well because some hosts do not provide a content-type. - # At some point we may want to use magic numbers to discover the content-type and reply a proper one. - defp proxy_request_content_type(headers, _body) do - headers["Content-Type"] || headers["content-type"] || "application/octet-stream" - end - - defp put_attachement_header(conn, true, _), do: conn - - defp put_attachement_header(conn, false, filename) do - put_resp_header(conn, "content-disposition", "attachment; filename='#{filename}'") - end end diff --git a/lib/pleroma/web/media_proxy/media_proxy.ex b/lib/pleroma/web/media_proxy/media_proxy.ex index 0fc0a07b2..a61726b3e 100644 --- a/lib/pleroma/web/media_proxy/media_proxy.ex +++ b/lib/pleroma/web/media_proxy/media_proxy.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.MediaProxy do @base64_opts [padding: false] @@ -14,13 +18,18 @@ defmodule Pleroma.Web.MediaProxy do url else secret = Application.get_env(:pleroma, Pleroma.Web.Endpoint)[:secret_key_base] - base64 = Base.url_encode64(url, @base64_opts) + + # The URL is url-decoded and encoded again to ensure it is correctly encoded and not twice. + base64 = + url + |> URI.decode() + |> URI.encode() + |> Base.url_encode64(@base64_opts) + sig = :crypto.hmac(:sha, secret, base64) sig64 = sig |> Base.url_encode64(@base64_opts) - filename = if path = URI.parse(url).path, do: "/" <> Path.basename(path), else: "" - Keyword.get(config, :base_url, Pleroma.Web.base_url()) <> - "/proxy/#{sig64}/#{base64}#{filename}" + build_url(sig64, base64, filename(url)) end end @@ -35,4 +44,20 @@ defmodule Pleroma.Web.MediaProxy do {:error, :invalid_signature} end end + + def filename(url_or_path) do + if path = URI.parse(url_or_path).path, do: Path.basename(path) + end + + def build_url(sig_base64, url_base64, filename \\ nil) do + [ + Pleroma.Config.get([:media_proxy, :base_url], Pleroma.Web.base_url()), + "proxy", + sig_base64, + url_base64, + filename + ] + |> Enum.filter(fn value -> value end) + |> Path.join() + end end diff --git a/lib/pleroma/web/nodeinfo/nodeinfo_controller.ex b/lib/pleroma/web/nodeinfo/nodeinfo_controller.ex index 151db0bb7..a992f75f6 100644 --- a/lib/pleroma/web/nodeinfo/nodeinfo_controller.ex +++ b/lib/pleroma/web/nodeinfo/nodeinfo_controller.ex @@ -1,9 +1,14 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.Nodeinfo.NodeinfoController do use Pleroma.Web, :controller alias Pleroma.Stats alias Pleroma.Web alias Pleroma.{User, Repo} + alias Pleroma.Config alias Pleroma.Web.ActivityPub.MRF plug(Pleroma.Web.FederatingPlug) @@ -52,6 +57,10 @@ defmodule Pleroma.Web.Nodeinfo.NodeinfoController do |> Repo.all() |> Enum.map(fn u -> u.ap_id end) + mrf_user_allowlist = + Config.get([:mrf_user_allowlist], []) + |> Enum.into(%{}, fn {k, v} -> {k, length(v)} end) + mrf_transparency = Keyword.get(instance, :mrf_transparency) federation_response = @@ -59,29 +68,35 @@ defmodule Pleroma.Web.Nodeinfo.NodeinfoController do %{ mrf_policies: mrf_policies, mrf_simple: mrf_simple, + mrf_user_allowlist: mrf_user_allowlist, quarantined_instances: quarantined } else %{} end - features = [ - "pleroma_api", - "mastodon_api", - "mastodon_api_streaming", - if Keyword.get(media_proxy, :enabled) do - "media_proxy" - end, - if Keyword.get(gopher, :enabled) do - "gopher" - end, - if Keyword.get(chat, :enabled) do - "chat" - end, - if Keyword.get(suggestions, :enabled) do - "suggestions" - end - ] + features = + [ + "pleroma_api", + "mastodon_api", + "mastodon_api_streaming", + if Keyword.get(media_proxy, :enabled) do + "media_proxy" + end, + if Keyword.get(gopher, :enabled) do + "gopher" + end, + if Keyword.get(chat, :enabled) do + "chat" + end, + if Keyword.get(suggestions, :enabled) do + "suggestions" + end, + if Keyword.get(instance, :allow_relay) do + "relay" + end + ] + |> Enum.filter(& &1) response = %{ version: "2.0", @@ -121,7 +136,10 @@ defmodule Pleroma.Web.Nodeinfo.NodeinfoController do banner: Keyword.get(instance, :banner_upload_limit), background: Keyword.get(instance, :background_upload_limit) }, - features: features + accountActivationRequired: Keyword.get(instance, :account_activation_required, false), + invitesEnabled: Keyword.get(instance, :invites_enabled, false), + features: features, + restrictedNicknames: Pleroma.Config.get([Pleroma.User, :restricted_nicknames]) } } diff --git a/lib/pleroma/web/oauth/app.ex b/lib/pleroma/web/oauth/app.ex index b3273bc6e..c18e9da8c 100644 --- a/lib/pleroma/web/oauth/app.ex +++ b/lib/pleroma/web/oauth/app.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.OAuth.App do use Ecto.Schema import Ecto.{Changeset} diff --git a/lib/pleroma/web/oauth/authorization.ex b/lib/pleroma/web/oauth/authorization.ex index 2cad4550a..7e75d71b3 100644 --- a/lib/pleroma/web/oauth/authorization.ex +++ b/lib/pleroma/web/oauth/authorization.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.OAuth.Authorization do use Ecto.Schema diff --git a/lib/pleroma/web/oauth/fallback_controller.ex b/lib/pleroma/web/oauth/fallback_controller.ex index 3927cdb64..e1d91dc80 100644 --- a/lib/pleroma/web/oauth/fallback_controller.ex +++ b/lib/pleroma/web/oauth/fallback_controller.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.OAuth.FallbackController do use Pleroma.Web, :controller alias Pleroma.Web.OAuth.OAuthController diff --git a/lib/pleroma/web/oauth/oauth_controller.ex b/lib/pleroma/web/oauth/oauth_controller.ex index d03c8b05a..41b0f253d 100644 --- a/lib/pleroma/web/oauth/oauth_controller.ex +++ b/lib/pleroma/web/oauth/oauth_controller.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.OAuth.OAuthController do use Pleroma.Web, :controller @@ -31,6 +35,7 @@ defmodule Pleroma.Web.OAuth.OAuthController do }) do with %User{} = user <- User.get_by_nickname_or_email(name), true <- Pbkdf2.checkpw(password, user.password_hash), + {:auth_active, true} <- {:auth_active, User.auth_active?(user)}, %App{} = app <- Repo.get_by(App, client_id: client_id), {:ok, auth} <- Authorization.create_authorization(app, user) do # Special case: Local MastodonFE. @@ -63,6 +68,15 @@ defmodule Pleroma.Web.OAuth.OAuthController do redirect(conn, external: url) end + else + {:auth_active, false} -> + conn + |> put_flash(:error, "Account confirmation pending") + |> put_status(:forbidden) + |> authorize(params) + + error -> + error end end @@ -101,6 +115,7 @@ defmodule Pleroma.Web.OAuth.OAuthController do with %App{} = app <- get_app_from_request(conn, params), %User{} = user <- User.get_by_nickname_or_email(name), true <- Pbkdf2.checkpw(password, user.password_hash), + {:auth_active, true} <- {:auth_active, User.auth_active?(user)}, {:ok, auth} <- Authorization.create_authorization(app, user), {:ok, token} <- Token.exchange_token(app, auth) do response = %{ @@ -113,6 +128,11 @@ defmodule Pleroma.Web.OAuth.OAuthController do json(conn, response) else + {:auth_active, false} -> + conn + |> put_status(:forbidden) + |> json(%{error: "Account confirmation pending"}) + _error -> put_status(conn, 400) |> json(%{error: "Invalid credentials"}) @@ -121,7 +141,7 @@ defmodule Pleroma.Web.OAuth.OAuthController do def token_exchange( conn, - %{"grant_type" => "password", "name" => name, "password" => password} = params + %{"grant_type" => "password", "name" => name, "password" => _password} = params ) do params = params diff --git a/lib/pleroma/web/oauth/oauth_view.ex b/lib/pleroma/web/oauth/oauth_view.ex index b3923fcf5..da6f72433 100644 --- a/lib/pleroma/web/oauth/oauth_view.ex +++ b/lib/pleroma/web/oauth/oauth_view.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.OAuth.OAuthView do use Pleroma.Web, :view import Phoenix.HTML.Form diff --git a/lib/pleroma/web/oauth/token.ex b/lib/pleroma/web/oauth/token.ex index a77d5af35..aa3610bb3 100644 --- a/lib/pleroma/web/oauth/token.ex +++ b/lib/pleroma/web/oauth/token.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.OAuth.Token do use Ecto.Schema diff --git a/lib/pleroma/web/ostatus/activity_representer.ex b/lib/pleroma/web/ostatus/activity_representer.ex index 537bd9f77..bd05c671b 100644 --- a/lib/pleroma/web/ostatus/activity_representer.ex +++ b/lib/pleroma/web/ostatus/activity_representer.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.OStatus.ActivityRepresenter do alias Pleroma.{Activity, User, Object} alias Pleroma.Web.OStatus.UserRepresenter diff --git a/lib/pleroma/web/ostatus/feed_representer.ex b/lib/pleroma/web/ostatus/feed_representer.ex index 279672673..2c2157173 100644 --- a/lib/pleroma/web/ostatus/feed_representer.ex +++ b/lib/pleroma/web/ostatus/feed_representer.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.OStatus.FeedRepresenter do alias Pleroma.Web.OStatus alias Pleroma.Web.OStatus.{UserRepresenter, ActivityRepresenter} diff --git a/lib/pleroma/web/ostatus/handlers/delete_handler.ex b/lib/pleroma/web/ostatus/handlers/delete_handler.ex index 6330d7f64..e7cf4cb54 100644 --- a/lib/pleroma/web/ostatus/handlers/delete_handler.ex +++ b/lib/pleroma/web/ostatus/handlers/delete_handler.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.OStatus.DeleteHandler do require Logger alias Pleroma.Web.XML diff --git a/lib/pleroma/web/ostatus/handlers/follow_handler.ex b/lib/pleroma/web/ostatus/handlers/follow_handler.ex index 162407e04..aef450935 100644 --- a/lib/pleroma/web/ostatus/handlers/follow_handler.ex +++ b/lib/pleroma/web/ostatus/handlers/follow_handler.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.OStatus.FollowHandler do alias Pleroma.Web.{XML, OStatus} alias Pleroma.Web.ActivityPub.ActivityPub diff --git a/lib/pleroma/web/ostatus/handlers/note_handler.ex b/lib/pleroma/web/ostatus/handlers/note_handler.ex index 0d4080291..7fd364b45 100644 --- a/lib/pleroma/web/ostatus/handlers/note_handler.ex +++ b/lib/pleroma/web/ostatus/handlers/note_handler.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.OStatus.NoteHandler do require Logger alias Pleroma.Web.{XML, OStatus} diff --git a/lib/pleroma/web/ostatus/handlers/unfollow_handler.ex b/lib/pleroma/web/ostatus/handlers/unfollow_handler.ex index a115bf4c8..bd86a54c7 100644 --- a/lib/pleroma/web/ostatus/handlers/unfollow_handler.ex +++ b/lib/pleroma/web/ostatus/handlers/unfollow_handler.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.OStatus.UnfollowHandler do alias Pleroma.Web.{XML, OStatus} alias Pleroma.Web.ActivityPub.ActivityPub diff --git a/lib/pleroma/web/ostatus/ostatus.ex b/lib/pleroma/web/ostatus/ostatus.ex index 1d0019d3b..cd5493e16 100644 --- a/lib/pleroma/web/ostatus/ostatus.ex +++ b/lib/pleroma/web/ostatus/ostatus.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.OStatus do @httpoison Application.get_env(:pleroma, :httpoison) @@ -226,25 +230,21 @@ defmodule Pleroma.Web.OStatus do old_data = %{ avatar: user.avatar, bio: user.bio, - name: user.name, - info: user.info + name: user.name } with false <- user.local, avatar <- make_avatar_object(doc), bio <- string_from_xpath("//author[1]/summary", doc), name <- string_from_xpath("//author[1]/poco:displayName", doc), - info <- - Map.put(user.info, "banner", make_avatar_object(doc, "header") || user.info["banner"]), new_data <- %{ avatar: avatar || old_data.avatar, name: name || old_data.name, - bio: bio || old_data.bio, - info: info || old_data.info + bio: bio || old_data.bio }, false <- new_data == old_data do change = Ecto.Changeset.change(user, new_data) - Repo.update(change) + User.update_and_set_cache(change) else _ -> {:ok, user} @@ -350,13 +350,10 @@ defmodule Pleroma.Web.OStatus do def fetch_activity_from_atom_url(url) do with true <- String.starts_with?(url, "http"), - {:ok, %{body: body, status_code: code}} when code in 200..299 <- + {:ok, %{body: body, status: code}} when code in 200..299 <- @httpoison.get( url, - [Accept: "application/atom+xml"], - follow_redirect: true, - timeout: 10000, - recv_timeout: 20000 + [{:Accept, "application/atom+xml"}] ) do Logger.debug("Got document from #{url}, handling...") handle_incoming(body) @@ -371,8 +368,7 @@ defmodule Pleroma.Web.OStatus do Logger.debug("Trying to fetch #{url}") with true <- String.starts_with?(url, "http"), - {:ok, %{body: body}} <- - @httpoison.get(url, [], follow_redirect: true, timeout: 10000, recv_timeout: 20000), + {:ok, %{body: body}} <- @httpoison.get(url, []), {:ok, atom_url} <- get_atom_url(body) do fetch_activity_from_atom_url(atom_url) else @@ -383,19 +379,14 @@ defmodule Pleroma.Web.OStatus do end def fetch_activity_from_url(url) do - try do - with {:ok, activities} when length(activities) > 0 <- fetch_activity_from_atom_url(url) do - {:ok, activities} - else - _e -> - with {:ok, activities} <- fetch_activity_from_html_url(url) do - {:ok, activities} - end - end - rescue - e -> - Logger.debug("Couldn't get #{url}: #{inspect(e)}") - {:error, "Couldn't get #{url}: #{inspect(e)}"} + with {:ok, [_ | _] = activities} <- fetch_activity_from_atom_url(url) do + {:ok, activities} + else + _e -> fetch_activity_from_html_url(url) end + rescue + e -> + Logger.debug("Couldn't get #{url}: #{inspect(e)}") + {:error, "Couldn't get #{url}: #{inspect(e)}"} end end diff --git a/lib/pleroma/web/ostatus/ostatus_controller.ex b/lib/pleroma/web/ostatus/ostatus_controller.ex index af6e22c2b..9ad702dd4 100644 --- a/lib/pleroma/web/ostatus/ostatus_controller.ex +++ b/lib/pleroma/web/ostatus/ostatus_controller.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.OStatus.OStatusController do use Pleroma.Web, :controller @@ -136,7 +140,7 @@ defmodule Pleroma.Web.OStatus.OStatusController do "html" -> conn |> put_resp_content_type("text/html") - |> send_file(200, Application.app_dir(:pleroma, "priv/static/index.html")) + |> send_file(200, Pleroma.Plugs.InstanceStatic.file_path("index.html")) _ -> represent_activity(conn, format, activity, user) @@ -157,7 +161,7 @@ defmodule Pleroma.Web.OStatus.OStatusController do conn, "activity+json", %Activity{data: %{"type" => "Create"}} = activity, - user + _user ) do object = Object.normalize(activity.data["object"]) @@ -166,7 +170,7 @@ defmodule Pleroma.Web.OStatus.OStatusController do |> json(ObjectView.render("object.json", %{object: object})) end - defp represent_activity(conn, "activity+json", _, _) do + defp represent_activity(_conn, "activity+json", _, _) do {:error, :not_found} end diff --git a/lib/pleroma/web/ostatus/user_representer.ex b/lib/pleroma/web/ostatus/user_representer.ex index 2e696506e..ef8371a2c 100644 --- a/lib/pleroma/web/ostatus/user_representer.ex +++ b/lib/pleroma/web/ostatus/user_representer.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.OStatus.UserRepresenter do alias Pleroma.User diff --git a/lib/pleroma/web/push/push.ex b/lib/pleroma/web/push/push.ex new file mode 100644 index 000000000..6459d4543 --- /dev/null +++ b/lib/pleroma/web/push/push.ex @@ -0,0 +1,138 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.Web.Push do + use GenServer + + alias Pleroma.{Repo, User} + alias Pleroma.Web.Push.Subscription + + require Logger + import Ecto.Query + + @types ["Create", "Follow", "Announce", "Like"] + + def start_link() do + GenServer.start_link(__MODULE__, :ok, name: __MODULE__) + end + + def vapid_config() do + Application.get_env(:web_push_encryption, :vapid_details, []) + end + + def enabled() do + case vapid_config() do + [] -> false + list when is_list(list) -> true + _ -> false + end + end + + def send(notification) do + if enabled() do + GenServer.cast(Pleroma.Web.Push, {:send, notification}) + end + end + + def init(:ok) do + if !enabled() do + Logger.warn(""" + VAPID key pair is not found. If you wish to enabled web push, please run + + mix web_push.gen.keypair + + and add the resulting output to your configuration file. + """) + + :ignore + else + {:ok, nil} + end + end + + def handle_cast( + {:send, %{activity: %{data: %{"type" => type}}, user_id: user_id} = notification}, + state + ) + when type in @types do + actor = User.get_cached_by_ap_id(notification.activity.data["actor"]) + + type = Pleroma.Activity.mastodon_notification_type(notification.activity) + + Subscription + |> where(user_id: ^user_id) + |> preload(:token) + |> Repo.all() + |> Enum.filter(fn subscription -> + get_in(subscription.data, ["alerts", type]) || false + end) + |> Enum.each(fn subscription -> + sub = %{ + keys: %{ + p256dh: subscription.key_p256dh, + auth: subscription.key_auth + }, + endpoint: subscription.endpoint + } + + body = + Jason.encode!(%{ + title: format_title(notification), + access_token: subscription.token.token, + body: format_body(notification, actor), + notification_id: notification.id, + notification_type: type, + icon: User.avatar_url(actor), + preferred_locale: "en" + }) + + case WebPushEncryption.send_web_push( + body, + sub, + Application.get_env(:web_push_encryption, :gcm_api_key) + ) do + {:ok, %{status_code: code}} when 400 <= code and code < 500 -> + Logger.debug("Removing subscription record") + Repo.delete!(subscription) + :ok + + {:ok, %{status_code: code}} when 200 <= code and code < 300 -> + :ok + + {:ok, %{status_code: code}} -> + Logger.error("Web Push Notification failed with code: #{code}") + :error + + _ -> + Logger.error("Web Push Notification failed with unknown error") + :error + end + end) + + {:noreply, state} + end + + def handle_cast({:send, _}, state) do + Logger.warn("Unknown notification type") + {:noreply, state} + end + + defp format_title(%{activity: %{data: %{"type" => type}}}) do + case type do + "Create" -> "New Mention" + "Follow" -> "New Follower" + "Announce" -> "New Repeat" + "Like" -> "New Favorite" + end + end + + defp format_body(%{activity: %{data: %{"type" => type}}}, actor) do + case type do + "Create" -> "@#{actor.nickname} has mentioned you" + "Follow" -> "@#{actor.nickname} has followed you" + "Announce" -> "@#{actor.nickname} has repeated your post" + "Like" -> "@#{actor.nickname} has favorited your post" + end + end +end diff --git a/lib/pleroma/web/push/subscription.ex b/lib/pleroma/web/push/subscription.ex new file mode 100644 index 000000000..65d28fee9 --- /dev/null +++ b/lib/pleroma/web/push/subscription.ex @@ -0,0 +1,80 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.Web.Push.Subscription do + use Ecto.Schema + import Ecto.Changeset + alias Pleroma.{Repo, User} + alias Pleroma.Web.OAuth.Token + alias Pleroma.Web.Push.Subscription + + schema "push_subscriptions" do + belongs_to(:user, User) + belongs_to(:token, Token) + field(:endpoint, :string) + field(:key_p256dh, :string) + field(:key_auth, :string) + field(:data, :map, default: %{}) + + timestamps() + end + + @supported_alert_types ~w[follow favourite mention reblog] + + defp alerts(%{"data" => %{"alerts" => alerts}}) do + alerts = Map.take(alerts, @supported_alert_types) + %{"alerts" => alerts} + end + + def create( + %User{} = user, + %Token{} = token, + %{ + "subscription" => %{ + "endpoint" => endpoint, + "keys" => %{"auth" => key_auth, "p256dh" => key_p256dh} + } + } = params + ) do + Repo.insert(%Subscription{ + user_id: user.id, + token_id: token.id, + endpoint: endpoint, + key_auth: ensure_base64_urlsafe(key_auth), + key_p256dh: ensure_base64_urlsafe(key_p256dh), + data: alerts(params) + }) + end + + def get(%User{id: user_id}, %Token{id: token_id}) do + Repo.get_by(Subscription, user_id: user_id, token_id: token_id) + end + + def update(user, token, params) do + get(user, token) + |> change(data: alerts(params)) + |> Repo.update() + end + + def delete(user, token) do + Repo.delete(get(user, token)) + end + + def delete_if_exists(user, token) do + case get(user, token) do + nil -> {:ok, nil} + sub -> Repo.delete(sub) + end + end + + # Some webpush clients (e.g. iOS Toot!) use an non urlsafe base64 as an encoding for the key. + # However, the web push rfs specify to use base64 urlsafe, and the `web_push_encryption` library we use + # requires the key to be properly encoded. So we just convert base64 to urlsafe base64. + defp ensure_base64_urlsafe(string) do + string + |> String.replace("+", "-") + |> String.replace("/", "_") + |> String.replace("=", "") + end +end diff --git a/lib/pleroma/web/router.ex b/lib/pleroma/web/router.ex index 09265954a..7ec0cabb3 100644 --- a/lib/pleroma/web/router.ex +++ b/lib/pleroma/web/router.ex @@ -1,8 +1,10 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.Router do use Pleroma.Web, :router - alias Pleroma.{Repo, User, Web.Router} - pipeline :api do plug(:accepts, ["json"]) plug(:fetch_session) @@ -40,6 +42,7 @@ defmodule Pleroma.Web.Router do plug(Pleroma.Plugs.SessionAuthenticationPlug) plug(Pleroma.Plugs.LegacyAuthenticationPlug) plug(Pleroma.Plugs.AuthenticationPlug) + plug(Pleroma.Plugs.AdminSecretAuthenticationPlug) plug(Pleroma.Plugs.UserEnabledPlug) plug(Pleroma.Plugs.SetUserSessionIdPlug) plug(Pleroma.Plugs.EnsureAuthenticatedPlug) @@ -87,17 +90,29 @@ defmodule Pleroma.Web.Router do plug(:accepts, ["html", "json"]) end + pipeline :mailbox_preview do + plug(:accepts, ["html"]) + + plug(:put_secure_browser_headers, %{ + "content-security-policy" => + "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline' 'unsafe-eval'" + }) + end + scope "/api/pleroma", Pleroma.Web.TwitterAPI do pipe_through(:pleroma_api) get("/password_reset/:token", UtilController, :show_password_reset) post("/password_reset", UtilController, :password_reset) get("/emoji", UtilController, :emoji) + get("/captcha", UtilController, :captcha) end scope "/api/pleroma/admin", Pleroma.Web.AdminAPI do pipe_through(:admin_api) delete("/user", AdminAPIController, :user_delete) post("/user", AdminAPIController, :user_create) + put("/users/tag", AdminAPIController, :tag_users) + delete("/users/tag", AdminAPIController, :untag_users) get("/permission_group/:nickname", AdminAPIController, :right_get) get("/permission_group/:nickname/:permission_group", AdminAPIController, :right_get) @@ -108,6 +123,8 @@ defmodule Pleroma.Web.Router do delete("/relay", AdminAPIController, :relay_unfollow) get("/invite_token", AdminAPIController, :get_invite_token) + post("/email_invite", AdminAPIController, :email_invite) + get("/password_reset", AdminAPIController, :get_password_reset) end @@ -198,6 +215,11 @@ defmodule Pleroma.Web.Router do put("/filters/:id", MastodonAPIController, :update_filter) delete("/filters/:id", MastodonAPIController, :delete_filter) + post("/push/subscription", MastodonAPIController, :create_push_subscription) + get("/push/subscription", MastodonAPIController, :get_push_subscription) + put("/push/subscription", MastodonAPIController, :update_push_subscription) + delete("/push/subscription", MastodonAPIController, :delete_push_subscription) + get("/suggestions", MastodonAPIController, :suggestions) get("/endorsements", MastodonAPIController, :empty_array) @@ -263,6 +285,16 @@ defmodule Pleroma.Web.Router do get("/statusnet/conversation/:id", TwitterAPI.Controller, :fetch_conversation) post("/account/register", TwitterAPI.Controller, :register) + post("/account/password_reset", TwitterAPI.Controller, :password_reset) + + get( + "/account/confirm_email/:user_id/:token", + TwitterAPI.Controller, + :confirm_email, + as: :confirm_email + ) + + post("/account/resend_confirmation_email", TwitterAPI.Controller, :resend_confirmation_email) get("/search", TwitterAPI.Controller, :search) get("/statusnet/tags/timeline/:tag", TwitterAPI.Controller, :public_and_external_timeline) @@ -297,12 +329,6 @@ defmodule Pleroma.Web.Router do post("/account/update_profile_banner", TwitterAPI.Controller, :update_banner) post("/qvitter/update_background_image", TwitterAPI.Controller, :update_background) - post( - "/account/most_recent_notification", - TwitterAPI.Controller, - :update_most_recent_notification - ) - get("/statuses/home_timeline", TwitterAPI.Controller, :friends_timeline) get("/statuses/friends_timeline", TwitterAPI.Controller, :friends_timeline) get("/statuses/mentions", TwitterAPI.Controller, :mentions_timeline) @@ -330,6 +356,7 @@ defmodule Pleroma.Web.Router do post("/statusnet/media/upload", TwitterAPI.Controller, :upload) post("/media/upload", TwitterAPI.Controller, :upload_json) + post("/media/metadata/create", TwitterAPI.Controller, :update_media) post("/favorites/create/:id", TwitterAPI.Controller, :favorite) post("/favorites/create", TwitterAPI.Controller, :favorite) @@ -424,6 +451,14 @@ defmodule Pleroma.Web.Router do get("/:sig/:url/:filename", MediaProxyController, :remote) end + if Mix.env() == :dev do + scope "/dev" do + pipe_through([:mailbox_preview]) + + forward("/mailbox", Plug.Swoosh.MailboxPreview, base_path: "/dev/mailbox") + end + end + scope "/", Fallback do get("/registration/:token", RedirectController, :registration_page) get("/*path", RedirectController, :redirector) @@ -438,7 +473,7 @@ defmodule Fallback.RedirectController do def redirector(conn, _params) do conn |> put_resp_content_type("text/html") - |> send_file(200, Application.app_dir(:pleroma, "priv/static/index.html")) + |> send_file(200, Pleroma.Plugs.InstanceStatic.file_path("index.html")) end def registration_page(conn, params) do diff --git a/lib/pleroma/web/salmon/salmon.ex b/lib/pleroma/web/salmon/salmon.ex index 562ec3d9c..1dc514976 100644 --- a/lib/pleroma/web/salmon/salmon.ex +++ b/lib/pleroma/web/salmon/salmon.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.Salmon do @httpoison Application.get_env(:pleroma, :httpoison) @@ -157,15 +161,12 @@ defmodule Pleroma.Web.Salmon do |> Enum.filter(fn user -> user && !user.local end) end - defp send_to_user(%{info: %{"salmon" => salmon}}, feed, poster) do - with {:ok, %{status_code: code}} <- + defp send_to_user(%{info: %{salmon: salmon}}, feed, poster) do + with {:ok, %{status: code}} <- poster.( salmon, feed, - [{"Content-Type", "application/magic-envelope+xml"}], - timeout: 10000, - recv_timeout: 20000, - hackney: [pool: :default] + [{"Content-Type", "application/magic-envelope+xml"}] ) do Logger.debug(fn -> "Pushed to #{salmon}, code #{code}" end) else @@ -183,9 +184,9 @@ defmodule Pleroma.Web.Salmon do "Undo", "Delete" ] - def publish(user, activity, poster \\ &@httpoison.post/4) + def publish(user, activity, poster \\ &@httpoison.post/3) - def publish(%{info: %{"keys" => keys}} = user, %{data: %{"type" => type}} = activity, poster) + def publish(%{info: %{keys: keys}} = user, %{data: %{"type" => type}} = activity, poster) when type in @supported_activities do feed = ActivityRepresenter.to_simple_form(activity, user, true) diff --git a/lib/pleroma/web/streamer.ex b/lib/pleroma/web/streamer.ex index 5cab62c85..05f877438 100644 --- a/lib/pleroma/web/streamer.ex +++ b/lib/pleroma/web/streamer.ex @@ -1,20 +1,16 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.Streamer do use GenServer require Logger alias Pleroma.{User, Notification, Activity, Object, Repo} alias Pleroma.Web.ActivityPub.ActivityPub - def init(args) do - {:ok, args} - end + @keepalive_interval :timer.seconds(30) def start_link do - spawn(fn -> - # 30 seconds - Process.sleep(1000 * 30) - GenServer.cast(__MODULE__, %{action: :ping}) - end) - GenServer.start_link(__MODULE__, %{}, name: __MODULE__) end @@ -30,6 +26,16 @@ defmodule Pleroma.Web.Streamer do GenServer.cast(__MODULE__, %{action: :stream, topic: topic, item: item}) end + def init(args) do + spawn(fn -> + # 30 seconds + Process.sleep(@keepalive_interval) + GenServer.cast(__MODULE__, %{action: :ping}) + end) + + {:ok, args} + end + def handle_cast(%{action: :ping}, topics) do Map.values(topics) |> List.flatten() @@ -40,7 +46,7 @@ defmodule Pleroma.Web.Streamer do spawn(fn -> # 30 seconds - Process.sleep(1000 * 30) + Process.sleep(@keepalive_interval) GenServer.cast(__MODULE__, %{action: :ping}) end) @@ -61,8 +67,6 @@ defmodule Pleroma.Web.Streamer do end def handle_cast(%{action: :stream, topic: "list", item: item}, topics) do - author = User.get_cached_by_ap_id(item.data["actor"]) - # filter the recipient list if the activity is not public, see #270. recipient_lists = case ActivityPub.is_public?(item) do @@ -73,7 +77,8 @@ defmodule Pleroma.Web.Streamer do Pleroma.List.get_lists_from_activity(item) |> Enum.filter(fn list -> owner = Repo.get(User, list.user_id) - author.follower_address in owner.following + + ActivityPub.visible_for_user?(item, owner) end) end @@ -187,7 +192,7 @@ defmodule Pleroma.Web.Streamer do # Get the current user so we have up-to-date blocks etc. if socket.assigns[:user] do user = User.get_cached_by_ap_id(socket.assigns[:user].ap_id) - blocks = user.info["blocks"] || [] + blocks = user.info.blocks || [] parent = Object.normalize(item.data["object"]) @@ -205,7 +210,7 @@ defmodule Pleroma.Web.Streamer do # Get the current user so we have up-to-date blocks etc. if socket.assigns[:user] do user = User.get_cached_by_ap_id(socket.assigns[:user].ap_id) - blocks = user.info["blocks"] || [] + blocks = user.info.blocks || [] unless item.actor in blocks do send(socket.transport_pid, {:text, represent_update(item, user)}) diff --git a/lib/pleroma/web/templates/layout/app.html.eex b/lib/pleroma/web/templates/layout/app.html.eex index 2a8dede80..2e96c1509 100644 --- a/lib/pleroma/web/templates/layout/app.html.eex +++ b/lib/pleroma/web/templates/layout/app.html.eex @@ -2,7 +2,9 @@ <html> <head> <meta charset=utf-8 /> - <title>Pleroma</title> + <title> + <%= Application.get_env(:pleroma, :instance)[:name] %> + </title> <style> body { background-color: #282c37; diff --git a/lib/pleroma/web/templates/twitter_api/util/password_reset_failed.html.eex b/lib/pleroma/web/templates/twitter_api/util/password_reset_failed.html.eex index 58a3736fd..df037c01e 100644 --- a/lib/pleroma/web/templates/twitter_api/util/password_reset_failed.html.eex +++ b/lib/pleroma/web/templates/twitter_api/util/password_reset_failed.html.eex @@ -1 +1,2 @@ <h2>Password reset failed</h2> +<h3><a href="<%= Pleroma.Web.base_url() %>">Homepage</a></h3> diff --git a/lib/pleroma/web/templates/twitter_api/util/password_reset_success.html.eex b/lib/pleroma/web/templates/twitter_api/util/password_reset_success.html.eex index c7dfcb6dd..f30ba3274 100644 --- a/lib/pleroma/web/templates/twitter_api/util/password_reset_success.html.eex +++ b/lib/pleroma/web/templates/twitter_api/util/password_reset_success.html.eex @@ -1 +1,2 @@ <h2>Password changed!</h2> +<h3><a href="<%= Pleroma.Web.base_url() %>">Homepage</a></h3> diff --git a/lib/pleroma/web/twitter_api/controllers/util_controller.ex b/lib/pleroma/web/twitter_api/controllers/util_controller.ex index b0ed8387e..c872aec2b 100644 --- a/lib/pleroma/web/twitter_api/controllers/util_controller.ex +++ b/lib/pleroma/web/twitter_api/controllers/util_controller.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.TwitterAPI.UtilController do use Pleroma.Web, :controller require Logger @@ -6,9 +10,8 @@ defmodule Pleroma.Web.TwitterAPI.UtilController do alias Pleroma.Web.WebFinger alias Pleroma.Web.CommonAPI alias Comeonin.Pbkdf2 - alias Pleroma.{Formatter, Emoji} alias Pleroma.Web.ActivityPub.ActivityPub - alias Pleroma.{Repo, PasswordResetToken, User} + alias Pleroma.{Repo, PasswordResetToken, User, Emoji} def show_password_reset(conn, %{"token" => token}) do with %{used: false} = token <- Repo.get_by(PasswordResetToken, %{token: token}), @@ -157,13 +160,27 @@ defmodule Pleroma.Web.TwitterAPI.UtilController do |> send_resp(200, response) _ -> + vapid_public_key = Keyword.get(Pleroma.Web.Push.vapid_config(), :public_key) + + uploadlimit = %{ + uploadlimit: to_string(Keyword.get(instance, :upload_limit)), + avatarlimit: to_string(Keyword.get(instance, :avatar_upload_limit)), + backgroundlimit: to_string(Keyword.get(instance, :background_upload_limit)), + bannerlimit: to_string(Keyword.get(instance, :banner_upload_limit)) + } + data = %{ name: Keyword.get(instance, :name), description: Keyword.get(instance, :description), server: Web.base_url(), textlimit: to_string(Keyword.get(instance, :limit)), + uploadlimit: uploadlimit, closed: if(Keyword.get(instance, :registrations_open), do: "0", else: "1"), - private: if(Keyword.get(instance, :public, true), do: "0", else: "1") + private: if(Keyword.get(instance, :public, true), do: "0", else: "1"), + vapidPublicKey: vapid_public_key, + accountActivationRequired: + if(Keyword.get(instance, :account_activation_required, false), do: "1", else: "0"), + invitesEnabled: if(Keyword.get(instance, :invites_enabled, false), do: "1", else: "0") } pleroma_fe = %{ @@ -180,7 +197,10 @@ defmodule Pleroma.Web.TwitterAPI.UtilController do formattingOptionsEnabled: Keyword.get(instance_fe, :formatting_options_enabled), collapseMessageWithSubject: Keyword.get(instance_fe, :collapse_message_with_subject), hidePostStats: Keyword.get(instance_fe, :hide_post_stats), - hideUserStats: Keyword.get(instance_fe, :hide_user_stats) + hideUserStats: Keyword.get(instance_fe, :hide_user_stats), + scopeCopy: Keyword.get(instance_fe, :scope_copy), + subjectLineBehavior: Keyword.get(instance_fe, :subject_line_behavior), + alwaysShowSubjectInput: Keyword.get(instance_fe, :always_show_subject_input) } managed_config = Keyword.get(instance, :managed_config) @@ -270,4 +290,8 @@ defmodule Pleroma.Web.TwitterAPI.UtilController do json(conn, %{error: msg}) end end + + def captcha(conn, _params) do + json(conn, Pleroma.Captcha.new()) + end end diff --git a/lib/pleroma/web/twitter_api/representers/activity_representer.ex b/lib/pleroma/web/twitter_api/representers/activity_representer.ex index fbd33f07e..489a55b6c 100644 --- a/lib/pleroma/web/twitter_api/representers/activity_representer.ex +++ b/lib/pleroma/web/twitter_api/representers/activity_representer.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + # THIS MODULE IS DEPRECATED! DON'T USE IT! # USE THE Pleroma.Web.TwitterAPI.Views.ActivityView MODULE! defmodule Pleroma.Web.TwitterAPI.Representers.ActivityRepresenter do @@ -141,7 +145,7 @@ defmodule Pleroma.Web.TwitterAPI.Representers.ActivityRepresenter do end def to_map( - %Activity{data: %{"object" => %{"content" => content} = object}} = activity, + %Activity{data: %{"object" => %{"content" => _content} = object}} = activity, %{user: user} = opts ) do created_at = object["published"] |> Utils.date_to_asctime() @@ -165,20 +169,13 @@ defmodule Pleroma.Web.TwitterAPI.Representers.ActivityRepresenter do tags = if possibly_sensitive, do: Enum.uniq(["nsfw" | tags]), else: tags - {summary, content} = ActivityView.render_content(object) + {_summary, content} = ActivityView.render_content(object) html = HTML.filter_tags(content, User.html_filter_policy(opts[:for])) |> Formatter.emojify(object["emoji"]) - video = - if object["type"] == "Video" do - vid = [object] - else - [] - end - - attachments = (object["attachment"] || []) ++ video + attachments = object["attachment"] || [] reply_parent = Activity.get_in_reply_to_activity(activity) diff --git a/lib/pleroma/web/twitter_api/representers/base_representer.ex b/lib/pleroma/web/twitter_api/representers/base_representer.ex index f32a21d47..28a59205d 100644 --- a/lib/pleroma/web/twitter_api/representers/base_representer.ex +++ b/lib/pleroma/web/twitter_api/representers/base_representer.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.TwitterAPI.Representers.BaseRepresenter do defmacro __using__(_opts) do quote do diff --git a/lib/pleroma/web/twitter_api/representers/object_representer.ex b/lib/pleroma/web/twitter_api/representers/object_representer.ex index d5291a397..2f33e7af4 100644 --- a/lib/pleroma/web/twitter_api/representers/object_representer.ex +++ b/lib/pleroma/web/twitter_api/representers/object_representer.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.TwitterAPI.Representers.ObjectRepresenter do use Pleroma.Web.TwitterAPI.Representers.BaseRepresenter alias Pleroma.Object diff --git a/lib/pleroma/web/twitter_api/twitter_api.ex b/lib/pleroma/web/twitter_api/twitter_api.ex index 5bfb83b1e..e2b1e0a8e 100644 --- a/lib/pleroma/web/twitter_api/twitter_api.ex +++ b/lib/pleroma/web/twitter_api/twitter_api.ex @@ -1,19 +1,22 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.TwitterAPI.TwitterAPI do alias Pleroma.{UserInviteToken, User, Activity, Repo, Object} + alias Pleroma.{UserEmail, Mailer} alias Pleroma.Web.ActivityPub.ActivityPub alias Pleroma.Web.TwitterAPI.UserView - alias Pleroma.Web.{OStatus, CommonAPI} - alias Pleroma.Web.MediaProxy - import Ecto.Query + alias Pleroma.Web.CommonAPI - @httpoison Application.get_env(:pleroma, :httpoison) + import Ecto.Query def create_status(%User{} = user, %{"status" => _} = data) do CommonAPI.post(user, data) end def delete(%User{} = user, id) do - with %Activity{data: %{"type" => type}} <- Repo.get(Activity, id), + with %Activity{data: %{"type" => _type}} <- Repo.get(Activity, id), {:ok, activity} <- CommonAPI.delete(id, user) do {:ok, activity} end @@ -37,7 +40,7 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPI do def unfollow(%User{} = follower, params) do with {:ok, %User{} = unfollowed} <- get_user(params), - {:ok, follower, follow_activity} <- User.unfollow(follower, unfollowed), + {:ok, follower, _follow_activity} <- User.unfollow(follower, unfollowed), {:ok, _activity} <- ActivityPub.unfollow(follower, unfollowed) do {:ok, follower, unfollowed} else @@ -93,11 +96,11 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPI do end end - def upload(%Plug.Upload{} = file, format \\ "xml") do - {:ok, object} = ActivityPub.upload(file) + def upload(%Plug.Upload{} = file, %User{} = user, format \\ "xml") do + {:ok, object} = ActivityPub.upload(file, actor: User.ap_id(user)) url = List.first(object.data["url"]) - href = url["href"] |> MediaProxy.url() + href = url["href"] type = url["mediaType"] case format do @@ -132,41 +135,78 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPI do params = %{ nickname: params["nickname"], name: params["fullname"], - bio: params["bio"], + bio: User.parse_bio(params["bio"]), email: params["email"], password: params["password"], - password_confirmation: params["confirm"] + password_confirmation: params["confirm"], + captcha_solution: params["captcha_solution"], + captcha_token: params["captcha_token"] } - registrations_open = Pleroma.Config.get([:instance, :registrations_open]) - - # no need to query DB if registration is open - token = - unless registrations_open || is_nil(tokenString) do - Repo.get_by(UserInviteToken, %{token: tokenString}) + captcha_enabled = Pleroma.Config.get([Pleroma.Captcha, :enabled]) + # true if captcha is disabled or enabled and valid, false otherwise + captcha_ok = + if !captcha_enabled do + true + else + Pleroma.Captcha.validate(params[:captcha_token], params[:captcha_solution]) end - cond do - registrations_open || (!is_nil(token) && !token.used) -> - changeset = User.register_changeset(%User{}, params) - - with {:ok, user} <- Repo.insert(changeset) do - !registrations_open && UserInviteToken.mark_as_used(token.token) - {:ok, user} - else - {:error, changeset} -> - errors = - Ecto.Changeset.traverse_errors(changeset, fn {msg, _opts} -> msg end) - |> Jason.encode!() + # Captcha invalid + if not captcha_ok do + # I have no idea how this error handling works + {:error, %{error: Jason.encode!(%{captcha: ["Invalid CAPTCHA"]})}} + else + registrations_open = Pleroma.Config.get([:instance, :registrations_open]) - {:error, %{error: errors}} + # no need to query DB if registration is open + token = + unless registrations_open || is_nil(tokenString) do + Repo.get_by(UserInviteToken, %{token: tokenString}) end - !registrations_open && is_nil(token) -> - {:error, "Invalid token"} + cond do + registrations_open || (!is_nil(token) && !token.used) -> + changeset = User.register_changeset(%User{}, params) + + with {:ok, user} <- User.register(changeset) do + !registrations_open && UserInviteToken.mark_as_used(token.token) + + {:ok, user} + else + {:error, changeset} -> + errors = + Ecto.Changeset.traverse_errors(changeset, fn {msg, _opts} -> msg end) + |> Jason.encode!() + + {:error, %{error: errors}} + end + + !registrations_open && is_nil(token) -> + {:error, "Invalid token"} - !registrations_open && token.used -> - {:error, "Expired token"} + !registrations_open && token.used -> + {:error, "Expired token"} + end + end + end + + def password_reset(nickname_or_email) do + with true <- is_binary(nickname_or_email), + %User{local: true} = user <- User.get_by_nickname_or_email(nickname_or_email), + {:ok, token_record} <- Pleroma.PasswordResetToken.create_token(user) do + user + |> UserEmail.password_reset_email(token_record.token) + |> Mailer.deliver() + else + false -> + {:error, "bad user identifier"} + + %User{local: false} -> + {:error, "remote user"} + + nil -> + {:error, "unknown user"} end end @@ -244,10 +284,6 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPI do _activities = Repo.all(q) end - defp make_date do - DateTime.utc_now() |> DateTime.to_iso8601() - end - # DEPRECATED mostly, context objects are now created at insertion time. def context_to_conversation_id(context) do with %Object{id: id} <- Object.get_cached_by_ap_id(context) do @@ -279,14 +315,6 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPI do def get_external_profile(for_user, uri) do with %User{} = user <- User.get_or_fetch(uri) do - spawn(fn -> - with url <- user.info["topic"], - {:ok, %{body: body}} <- - @httpoison.get(url, [], follow_redirect: true, timeout: 10000, recv_timeout: 20000) do - OStatus.handle_incoming(body) - end - end) - {:ok, UserView.render("show.json", %{user: user, for: for_user})} else _e -> diff --git a/lib/pleroma/web/twitter_api/twitter_api_controller.ex b/lib/pleroma/web/twitter_api/twitter_api_controller.ex index cd0e2121c..92b7386da 100644 --- a/lib/pleroma/web/twitter_api/twitter_api_controller.ex +++ b/lib/pleroma/web/twitter_api/twitter_api_controller.ex @@ -1,10 +1,15 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.TwitterAPI.Controller do use Pleroma.Web, :controller - alias Pleroma.Formatter + + import Pleroma.Web.ControllerHelper, only: [json_response: 3] + alias Pleroma.Web.TwitterAPI.{TwitterAPI, UserView, ActivityView, NotificationView} alias Pleroma.Web.CommonAPI - alias Pleroma.Web.CommonAPI.Utils, as: CommonUtils - alias Pleroma.{Repo, Activity, User, Notification} + alias Pleroma.{Repo, Activity, Object, User, Notification} alias Pleroma.Web.ActivityPub.ActivityPub alias Pleroma.Web.ActivityPub.Utils alias Ecto.Changeset @@ -16,7 +21,10 @@ defmodule Pleroma.Web.TwitterAPI.Controller do def verify_credentials(%{assigns: %{user: user}} = conn, _params) do token = Phoenix.Token.sign(conn, "user socket", user.id) - render(conn, UserView, "show.json", %{user: user, token: token}) + + conn + |> put_view(UserView) + |> render("show.json", %{user: user, token: token}) end def status_update(%{assigns: %{user: user}} = conn, %{"status" => _} = status_data) do @@ -57,7 +65,8 @@ defmodule Pleroma.Web.TwitterAPI.Controller do activities = ActivityPub.fetch_public_activities(params) conn - |> render(ActivityView, "index.json", %{activities: activities, for: user}) + |> put_view(ActivityView) + |> render("index.json", %{activities: activities, for: user}) end def public_timeline(%{assigns: %{user: user}} = conn, params) do @@ -70,7 +79,8 @@ defmodule Pleroma.Web.TwitterAPI.Controller do activities = ActivityPub.fetch_public_activities(params) conn - |> render(ActivityView, "index.json", %{activities: activities, for: user}) + |> put_view(ActivityView) + |> render("index.json", %{activities: activities, for: user}) end def friends_timeline(%{assigns: %{user: user}} = conn, params) do @@ -85,29 +95,55 @@ defmodule Pleroma.Web.TwitterAPI.Controller do |> ActivityPub.contain_timeline(user) conn - |> render(ActivityView, "index.json", %{activities: activities, for: user}) + |> put_view(ActivityView) + |> render("index.json", %{activities: activities, for: user}) end def show_user(conn, params) do - with {:ok, shown} <- TwitterAPI.get_user(params) do - if user = conn.assigns.user do - render(conn, UserView, "show.json", %{user: shown, for: user}) - else - render(conn, UserView, "show.json", %{user: shown}) - end + for_user = conn.assigns.user + + with {:ok, shown} <- TwitterAPI.get_user(params), + true <- + User.auth_active?(shown) || + (for_user && (for_user.id == shown.id || User.superuser?(for_user))) do + params = + if for_user do + %{user: shown, for: for_user} + else + %{user: shown} + end + + conn + |> put_view(UserView) + |> render("show.json", params) else {:error, msg} -> bad_request_reply(conn, msg) + + false -> + conn + |> put_status(404) + |> json(%{error: "Unconfirmed user"}) end end def user_timeline(%{assigns: %{user: user}} = conn, params) do case TwitterAPI.get_user(user, params) do {:ok, target_user} -> + # Twitter and ActivityPub use a different name and sense for this parameter. + {include_rts, params} = Map.pop(params, "include_rts") + + params = + case include_rts do + x when x == "false" or x == "0" -> Map.put(params, "exclude_reblogs", "true") + _ -> params + end + activities = ActivityPub.fetch_user_activities(target_user, user, params) conn - |> render(ActivityView, "index.json", %{activities: activities, for: user}) + |> put_view(ActivityView) + |> render("index.json", %{activities: activities, for: user}) {:error, msg} -> bad_request_reply(conn, msg) @@ -123,7 +159,8 @@ defmodule Pleroma.Web.TwitterAPI.Controller do activities = ActivityPub.fetch_activities([user.ap_id], params) conn - |> render(ActivityView, "index.json", %{activities: activities, for: user}) + |> put_view(ActivityView) + |> render("index.json", %{activities: activities, for: user}) end def dm_timeline(%{assigns: %{user: user}} = conn, params) do @@ -136,14 +173,16 @@ defmodule Pleroma.Web.TwitterAPI.Controller do activities = Repo.all(query) conn - |> render(ActivityView, "index.json", %{activities: activities, for: user}) + |> put_view(ActivityView) + |> render("index.json", %{activities: activities, for: user}) end def notifications(%{assigns: %{user: user}} = conn, params) do notifications = Notification.for_user(user, params) conn - |> render(NotificationView, "notification.json", %{notifications: notifications, for: user}) + |> put_view(NotificationView) + |> render("notification.json", %{notifications: notifications, for: user}) end def notifications_read(%{assigns: %{user: user}} = conn, %{"latest_id" => latest_id} = params) do @@ -152,17 +191,20 @@ defmodule Pleroma.Web.TwitterAPI.Controller do notifications = Notification.for_user(user, params) conn - |> render(NotificationView, "notification.json", %{notifications: notifications, for: user}) + |> put_view(NotificationView) + |> render("notification.json", %{notifications: notifications, for: user}) end - def notifications_read(%{assigns: %{user: user}} = conn, _) do + def notifications_read(%{assigns: %{user: _user}} = conn, _) do bad_request_reply(conn, "You need to specify latest_id") end def follow(%{assigns: %{user: user}} = conn, params) do case TwitterAPI.follow(user, params) do {:ok, user, followed, _activity} -> - render(conn, UserView, "show.json", %{user: followed, for: user}) + conn + |> put_view(UserView) + |> render("show.json", %{user: followed, for: user}) {:error, msg} -> forbidden_json_reply(conn, msg) @@ -172,7 +214,9 @@ defmodule Pleroma.Web.TwitterAPI.Controller do def block(%{assigns: %{user: user}} = conn, params) do case TwitterAPI.block(user, params) do {:ok, user, blocked} -> - render(conn, UserView, "show.json", %{user: blocked, for: user}) + conn + |> put_view(UserView) + |> render("show.json", %{user: blocked, for: user}) {:error, msg} -> forbidden_json_reply(conn, msg) @@ -182,7 +226,9 @@ defmodule Pleroma.Web.TwitterAPI.Controller do def unblock(%{assigns: %{user: user}} = conn, params) do case TwitterAPI.unblock(user, params) do {:ok, user, blocked} -> - render(conn, UserView, "show.json", %{user: blocked, for: user}) + conn + |> put_view(UserView) + |> render("show.json", %{user: blocked, for: user}) {:error, msg} -> forbidden_json_reply(conn, msg) @@ -191,14 +237,18 @@ defmodule Pleroma.Web.TwitterAPI.Controller do def delete_post(%{assigns: %{user: user}} = conn, %{"id" => id}) do with {:ok, activity} <- TwitterAPI.delete(user, id) do - render(conn, ActivityView, "activity.json", %{activity: activity, for: user}) + conn + |> put_view(ActivityView) + |> render("activity.json", %{activity: activity, for: user}) end end def unfollow(%{assigns: %{user: user}} = conn, params) do case TwitterAPI.unfollow(user, params) do {:ok, user, unfollowed} -> - render(conn, UserView, "show.json", %{user: unfollowed, for: user}) + conn + |> put_view(UserView) + |> render("show.json", %{user: unfollowed, for: user}) {:error, msg} -> forbidden_json_reply(conn, msg) @@ -208,7 +258,9 @@ defmodule Pleroma.Web.TwitterAPI.Controller do def fetch_status(%{assigns: %{user: user}} = conn, %{"id" => id}) do with %Activity{} = activity <- Repo.get(Activity, id), true <- ActivityPub.visible_for_user?(activity, user) do - render(conn, ActivityView, "activity.json", %{activity: activity, for: user}) + conn + |> put_view(ActivityView) + |> render("activity.json", %{activity: activity, for: user}) end end @@ -222,20 +274,56 @@ defmodule Pleroma.Web.TwitterAPI.Controller do "user" => user }) do conn - |> render(ActivityView, "index.json", %{activities: activities, for: user}) + |> put_view(ActivityView) + |> render("index.json", %{activities: activities, for: user}) end end - def upload(conn, %{"media" => media}) do - response = TwitterAPI.upload(media) + @doc """ + Updates metadata of uploaded media object. + Derived from [Twitter API endpoint](https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-metadata-create). + """ + def update_media(%{assigns: %{user: user}} = conn, %{"media_id" => id} = data) do + object = Repo.get(Object, id) + description = get_in(data, ["alt_text", "text"]) || data["name"] || data["description"] + + {conn, status, response_body} = + cond do + !object -> + {halt(conn), :not_found, ""} + + !Object.authorize_mutation(object, user) -> + {halt(conn), :forbidden, "You can only update your own uploads."} + + !is_binary(description) -> + {conn, :not_modified, ""} + + true -> + new_data = Map.put(object.data, "name", description) + + {:ok, _} = + object + |> Object.change(%{data: new_data}) + |> Repo.update() + + {conn, :no_content, ""} + end + + conn + |> put_status(status) + |> json(response_body) + end + + def upload(%{assigns: %{user: user}} = conn, %{"media" => media}) do + response = TwitterAPI.upload(media, user) conn |> put_resp_content_type("application/atom+xml") |> send_resp(200, response) end - def upload_json(conn, %{"media" => media}) do - response = TwitterAPI.upload(media, "json") + def upload_json(%{assigns: %{user: user}} = conn, %{"media" => media}) do + response = TwitterAPI.upload(media, user, "json") conn |> json_reply(200, response) @@ -254,34 +342,44 @@ defmodule Pleroma.Web.TwitterAPI.Controller do def favorite(%{assigns: %{user: user}} = conn, %{"id" => id}) do with {_, {:ok, id}} <- {:param_cast, Ecto.Type.cast(:integer, id)}, {:ok, activity} <- TwitterAPI.fav(user, id) do - render(conn, ActivityView, "activity.json", %{activity: activity, for: user}) + conn + |> put_view(ActivityView) + |> render("activity.json", %{activity: activity, for: user}) end end def unfavorite(%{assigns: %{user: user}} = conn, %{"id" => id}) do with {_, {:ok, id}} <- {:param_cast, Ecto.Type.cast(:integer, id)}, {:ok, activity} <- TwitterAPI.unfav(user, id) do - render(conn, ActivityView, "activity.json", %{activity: activity, for: user}) + conn + |> put_view(ActivityView) + |> render("activity.json", %{activity: activity, for: user}) end end def retweet(%{assigns: %{user: user}} = conn, %{"id" => id}) do with {_, {:ok, id}} <- {:param_cast, Ecto.Type.cast(:integer, id)}, {:ok, activity} <- TwitterAPI.repeat(user, id) do - render(conn, ActivityView, "activity.json", %{activity: activity, for: user}) + conn + |> put_view(ActivityView) + |> render("activity.json", %{activity: activity, for: user}) end end def unretweet(%{assigns: %{user: user}} = conn, %{"id" => id}) do with {_, {:ok, id}} <- {:param_cast, Ecto.Type.cast(:integer, id)}, {:ok, activity} <- TwitterAPI.unrepeat(user, id) do - render(conn, ActivityView, "activity.json", %{activity: activity, for: user}) + conn + |> put_view(ActivityView) + |> render("activity.json", %{activity: activity, for: user}) end end def register(conn, params) do with {:ok, user} <- TwitterAPI.register_user(params) do - render(conn, UserView, "show.json", %{user: user}) + conn + |> put_view(UserView) + |> render("show.json", %{user: user}) else {:error, errors} -> conn @@ -289,28 +387,54 @@ defmodule Pleroma.Web.TwitterAPI.Controller do end end - def update_avatar(%{assigns: %{user: user}} = conn, params) do - upload_limit = - Application.get_env(:pleroma, :instance) - |> Keyword.fetch(:avatar_upload_limit) + def password_reset(conn, params) do + nickname_or_email = params["email"] || params["nickname"] + + with {:ok, _} <- TwitterAPI.password_reset(nickname_or_email) do + json_response(conn, :no_content, "") + end + end + + def confirm_email(conn, %{"user_id" => uid, "token" => token}) do + with %User{} = user <- Repo.get(User, uid), + true <- user.local, + true <- user.info.confirmation_pending, + true <- user.info.confirmation_token == token, + info_change <- User.Info.confirmation_changeset(user.info, :confirmed), + changeset <- Changeset.change(user) |> Changeset.put_embed(:info, info_change), + {:ok, _} <- User.update_and_set_cache(changeset) do + conn + |> redirect(to: "/") + end + end + + def resend_confirmation_email(conn, params) do + nickname_or_email = params["email"] || params["nickname"] - {:ok, object} = ActivityPub.upload(params, upload_limit) + with %User{} = user <- User.get_by_nickname_or_email(nickname_or_email), + {:ok, _} <- User.try_send_confirmation_email(user) do + conn + |> json_response(:no_content, "") + end + end + + def update_avatar(%{assigns: %{user: user}} = conn, params) do + {:ok, object} = ActivityPub.upload(params, type: :avatar) change = Changeset.change(user, %{avatar: object.data}) {:ok, user} = User.update_and_set_cache(change) CommonAPI.update(user) - render(conn, UserView, "show.json", %{user: user, for: user}) + conn + |> put_view(UserView) + |> render("show.json", %{user: user, for: user}) end def update_banner(%{assigns: %{user: user}} = conn, params) do - upload_limit = - Application.get_env(:pleroma, :instance) - |> Keyword.fetch(:banner_upload_limit) - - with {:ok, object} <- ActivityPub.upload(%{"img" => params["banner"]}, upload_limit), - new_info <- Map.put(user.info, "banner", object.data), - change <- User.info_changeset(user, %{info: new_info}), - {:ok, user} <- User.update_and_set_cache(change) do + with {:ok, object} <- ActivityPub.upload(%{"img" => params["banner"]}, type: :banner), + new_info <- %{"banner" => object.data}, + info_cng <- User.Info.profile_update(user.info, new_info), + changeset <- Ecto.Changeset.change(user) |> Ecto.Changeset.put_embed(:info, info_cng), + {:ok, user} <- User.update_and_set_cache(changeset) do CommonAPI.update(user) %{"url" => [%{"href" => href} | _]} = object.data response = %{url: href} |> Jason.encode!() @@ -321,14 +445,11 @@ defmodule Pleroma.Web.TwitterAPI.Controller do end def update_background(%{assigns: %{user: user}} = conn, params) do - upload_limit = - Application.get_env(:pleroma, :instance) - |> Keyword.fetch(:background_upload_limit) - - with {:ok, object} <- ActivityPub.upload(params, upload_limit), - new_info <- Map.put(user.info, "background", object.data), - change <- User.info_changeset(user, %{info: new_info}), - {:ok, _user} <- User.update_and_set_cache(change) do + with {:ok, object} <- ActivityPub.upload(params, type: :background), + new_info <- %{"background" => object.data}, + info_cng <- User.Info.profile_update(user.info, new_info), + changeset <- Ecto.Changeset.change(user) |> Ecto.Changeset.put_embed(:info, info_cng), + {:ok, _user} <- User.update_and_set_cache(changeset) do %{"url" => [%{"href" => href} | _]} = object.data response = %{url: href} |> Jason.encode!() @@ -350,33 +471,37 @@ defmodule Pleroma.Web.TwitterAPI.Controller do end end - def update_most_recent_notification(%{assigns: %{user: user}} = conn, %{"id" => id}) do - with id when is_number(id) <- String.to_integer(id), - info <- user.info, - mrn <- max(id, user.info["most_recent_notification"] || 0), - updated_info <- Map.put(info, "most_recent_notification", mrn), - changeset <- User.info_changeset(user, %{info: updated_info}), - {:ok, _user} <- User.update_and_set_cache(changeset) do - conn - |> json_reply(200, Jason.encode!(mrn)) - else - _e -> bad_request_reply(conn, "Can't update.") - end - end - - def followers(conn, params) do - with {:ok, user} <- TwitterAPI.get_user(conn.assigns[:user], params), + def followers(%{assigns: %{user: for_user}} = conn, params) do + with {:ok, user} <- TwitterAPI.get_user(for_user, params), {:ok, followers} <- User.get_followers(user) do - render(conn, UserView, "index.json", %{users: followers, for: conn.assigns[:user]}) + followers = + cond do + for_user && user.id == for_user.id -> followers + user.info.hide_network -> [] + true -> followers + end + + conn + |> put_view(UserView) + |> render("index.json", %{users: followers, for: conn.assigns[:user]}) else _e -> bad_request_reply(conn, "Can't get followers") end end - def friends(conn, params) do + def friends(%{assigns: %{user: for_user}} = conn, params) do with {:ok, user} <- TwitterAPI.get_user(conn.assigns[:user], params), {:ok, friends} <- User.get_friends(user) do - render(conn, UserView, "index.json", %{users: friends, for: conn.assigns[:user]}) + friends = + cond do + for_user && user.id == for_user.id -> friends + user.info.hide_network -> [] + true -> friends + end + + conn + |> put_view(UserView) + |> render("index.json", %{users: friends, for: conn.assigns[:user]}) else _e -> bad_request_reply(conn, "Can't get friends") end @@ -385,13 +510,15 @@ defmodule Pleroma.Web.TwitterAPI.Controller do def friend_requests(conn, params) do with {:ok, user} <- TwitterAPI.get_user(conn.assigns[:user], params), {:ok, friend_requests} <- User.get_follow_requests(user) do - render(conn, UserView, "index.json", %{users: friend_requests, for: conn.assigns[:user]}) + conn + |> put_view(UserView) + |> render("index.json", %{users: friend_requests, for: conn.assigns[:user]}) else _e -> bad_request_reply(conn, "Can't get friend requests") end end - def approve_friend_request(conn, %{"user_id" => uid} = params) do + def approve_friend_request(conn, %{"user_id" => uid} = _params) do with followed <- conn.assigns[:user], uid when is_number(uid) <- String.to_integer(uid), %User{} = follower <- Repo.get(User, uid), @@ -405,13 +532,15 @@ defmodule Pleroma.Web.TwitterAPI.Controller do object: follow_activity.data["id"], type: "Accept" }) do - render(conn, UserView, "show.json", %{user: follower, for: followed}) + conn + |> put_view(UserView) + |> render("show.json", %{user: follower, for: followed}) else e -> bad_request_reply(conn, "Can't approve user: #{inspect(e)}") end end - def deny_friend_request(conn, %{"user_id" => uid} = params) do + def deny_friend_request(conn, %{"user_id" => uid} = _params) do with followed <- conn.assigns[:user], uid when is_number(uid) <- String.to_integer(uid), %User{} = follower <- Repo.get(User, uid), @@ -424,7 +553,9 @@ defmodule Pleroma.Web.TwitterAPI.Controller do object: follow_activity.data["id"], type: "Reject" }) do - render(conn, UserView, "show.json", %{user: follower, for: followed}) + conn + |> put_view(UserView) + |> render("show.json", %{user: follower, for: followed}) else e -> bad_request_reply(conn, "Can't deny user: #{inspect(e)}") end @@ -451,70 +582,47 @@ defmodule Pleroma.Web.TwitterAPI.Controller do json(conn, []) end - def update_profile(%{assigns: %{user: user}} = conn, params) do - params = - if bio = params["description"] do - mentions = Formatter.parse_mentions(bio) - tags = Formatter.parse_tags(bio) - - emoji = - (user.info["source_data"]["tag"] || []) - |> Enum.filter(fn %{"type" => t} -> t == "Emoji" end) - |> Enum.map(fn %{"icon" => %{"url" => url}, "name" => name} -> - {String.trim(name, ":"), url} - end) - - bio_html = CommonUtils.format_input(bio, mentions, tags, "text/plain") - Map.put(params, "bio", bio_html |> Formatter.emojify(emoji)) - else - params - end - - user = - if locked = params["locked"] do - with locked <- locked == "true", - new_info <- Map.put(user.info, "locked", locked), - change <- User.info_changeset(user, %{info: new_info}), - {:ok, user} <- User.update_and_set_cache(change) do - user + defp build_info_cng(user, params) do + info_params = + ["no_rich_text", "locked", "hide_network"] + |> Enum.reduce(%{}, fn key, res -> + if value = params[key] do + Map.put(res, key, value == "true") else - _e -> user + res end - else - user - end + end) - user = - if no_rich_text = params["no_rich_text"] do - with no_rich_text <- no_rich_text == "true", - new_info <- Map.put(user.info, "no_rich_text", no_rich_text), - change <- User.info_changeset(user, %{info: new_info}), - {:ok, user} <- User.update_and_set_cache(change) do - user - else - _e -> user - end + info_params = + if value = params["default_scope"] do + Map.put(info_params, "default_scope", value) else - user + info_params end - user = - if default_scope = params["default_scope"] do - with new_info <- Map.put(user.info, "default_scope", default_scope), - change <- User.info_changeset(user, %{info: new_info}), - {:ok, user} <- User.update_and_set_cache(change) do - user - else - _e -> user - end - else - user - end + User.Info.profile_update(user.info, info_params) + end + + defp parse_profile_bio(user, params) do + if bio = params["description"] do + Map.put(params, "bio", User.parse_bio(bio, user)) + else + params + end + end + + def update_profile(%{assigns: %{user: user}} = conn, params) do + params = parse_profile_bio(user, params) + info_cng = build_info_cng(user, params) with changeset <- User.update_changeset(user, params), + changeset <- Ecto.Changeset.put_embed(changeset, :info, info_cng), {:ok, user} <- User.update_and_set_cache(changeset) do CommonAPI.update(user) - render(conn, UserView, "user.json", %{user: user, for: user}) + + conn + |> put_view(UserView) + |> render("user.json", %{user: user, for: user}) else error -> Logger.debug("Can't update user: #{inspect(error)}") @@ -526,14 +634,16 @@ defmodule Pleroma.Web.TwitterAPI.Controller do activities = TwitterAPI.search(user, params) conn - |> render(ActivityView, "index.json", %{activities: activities, for: user}) + |> put_view(ActivityView) + |> render("index.json", %{activities: activities, for: user}) end def search_user(%{assigns: %{user: user}} = conn, %{"query" => query}) do users = User.search(query, true) conn - |> render(UserView, "index.json", %{users: users, for: user}) + |> put_view(UserView) + |> render("index.json", %{users: users, for: user}) end defp bad_request_reply(conn, error_message) do @@ -552,7 +662,7 @@ defmodule Pleroma.Web.TwitterAPI.Controller do json_reply(conn, 403, json) end - def only_if_public_instance(conn = %{conn: %{assigns: %{user: _user}}}, _), do: conn + def only_if_public_instance(%{assigns: %{user: %User{}}} = conn, _), do: conn def only_if_public_instance(conn, _) do if Keyword.get(Application.get_env(:pleroma, :instance), :public) do diff --git a/lib/pleroma/web/twitter_api/views/activity_view.ex b/lib/pleroma/web/twitter_api/views/activity_view.ex index 83e8fb765..592cf622f 100644 --- a/lib/pleroma/web/twitter_api/views/activity_view.ex +++ b/lib/pleroma/web/twitter_api/views/activity_view.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.TwitterAPI.ActivityView do use Pleroma.Web, :view alias Pleroma.Web.CommonAPI.Utils @@ -14,6 +18,7 @@ defmodule Pleroma.Web.TwitterAPI.ActivityView do alias Pleroma.HTML import Ecto.Query + require Logger defp query_context_ids([]), do: [] @@ -190,6 +195,11 @@ defmodule Pleroma.Web.TwitterAPI.ActivityView do text = "#{user.nickname} favorited a status." + favorited_status = + if liked_activity, + do: render("activity.json", Map.merge(opts, %{activity: liked_activity})), + else: nil + %{ "id" => activity.id, "user" => UserView.render("show.json", %{user: user, for: opts[:for]}), @@ -199,6 +209,7 @@ defmodule Pleroma.Web.TwitterAPI.ActivityView do "is_post_verb" => false, "uri" => "tag:#{activity.data["id"]}:objectType=Favourite", "created_at" => created_at, + "favorited_status" => favorited_status, "in_reply_to_status_id" => liked_activity_id, "external_url" => activity.data["id"], "activity_type" => "like" @@ -233,9 +244,17 @@ defmodule Pleroma.Web.TwitterAPI.ActivityView do {summary, content} = render_content(object) html = - HTML.filter_tags(content, User.html_filter_policy(opts[:for])) + content + |> HTML.filter_tags(User.html_filter_policy(opts[:for])) |> Formatter.emojify(object["emoji"]) + text = + if content do + content + |> String.replace(~r/<br\s?\/?>/, "\n") + |> HTML.strip_tags() + end + reply_parent = Activity.get_in_reply_to_activity(activity) reply_user = reply_parent && User.get_cached_by_ap_id(reply_parent.actor) @@ -245,7 +264,7 @@ defmodule Pleroma.Web.TwitterAPI.ActivityView do "uri" => activity.data["object"]["id"], "user" => UserView.render("show.json", %{user: user, for: opts[:for]}), "statusnet_html" => html, - "text" => HTML.strip_tags(content), + "text" => text, "is_local" => activity.local, "is_post_verb" => true, "created_at" => created_at, @@ -270,6 +289,11 @@ defmodule Pleroma.Web.TwitterAPI.ActivityView do } end + def render("activity.json", %{activity: unhandled_activity}) do + Logger.warn("#{__MODULE__} unhandled activity: #{inspect(unhandled_activity)}") + nil + end + def render_content(%{"type" => "Note"} = object) do summary = object["summary"] @@ -283,7 +307,8 @@ defmodule Pleroma.Web.TwitterAPI.ActivityView do {summary, content} end - def render_content(%{"type" => object_type} = object) when object_type in ["Article", "Page"] do + def render_content(%{"type" => object_type} = object) + when object_type in ["Article", "Page", "Video"] do summary = object["name"] || object["summary"] content = diff --git a/lib/pleroma/web/twitter_api/views/notification_view.ex b/lib/pleroma/web/twitter_api/views/notification_view.ex index 9eeb3afdc..d889038a2 100644 --- a/lib/pleroma/web/twitter_api/views/notification_view.ex +++ b/lib/pleroma/web/twitter_api/views/notification_view.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.TwitterAPI.NotificationView do use Pleroma.Web, :view alias Pleroma.{Notification, User} diff --git a/lib/pleroma/web/twitter_api/views/user_view.ex b/lib/pleroma/web/twitter_api/views/user_view.ex index a100a1127..6e489624f 100644 --- a/lib/pleroma/web/twitter_api/views/user_view.ex +++ b/lib/pleroma/web/twitter_api/views/user_view.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.TwitterAPI.UserView do use Pleroma.Web, :view alias Pleroma.User @@ -31,7 +35,7 @@ defmodule Pleroma.Web.TwitterAPI.UserView do user_info = User.get_cached_user_info(user) emoji = - (user.info["source_data"]["tag"] || []) + (user.info.source_data["tag"] || []) |> Enum.filter(fn %{"type" => t} -> t == "Emoji" end) |> Enum.map(fn %{"icon" => %{"url" => url}, "name" => name} -> {String.trim(name, ":"), url} @@ -40,7 +44,7 @@ defmodule Pleroma.Web.TwitterAPI.UserView do # ``fields`` is an array of mastodon profile field, containing ``{"name": "…", "value": "…"}``. # For example: [{"name": "Pronoun", "value": "she/her"}, …] fields = - (user.info["source_data"]["attachment"] || []) + (user.info.source_data["attachment"] || []) |> Enum.filter(fn %{"type" => t} -> t == "PropertyValue" end) |> Enum.map(fn fields -> Map.take(fields, ["name", "value"]) end) @@ -66,22 +70,28 @@ defmodule Pleroma.Web.TwitterAPI.UserView do "profile_image_url_profile_size" => image, "profile_image_url_original" => image, "rights" => %{ - "delete_others_notice" => !!user.info["is_moderator"] + "delete_others_notice" => !!user.info.is_moderator }, "screen_name" => user.nickname, "statuses_count" => user_info[:note_count], "statusnet_profile_url" => user.ap_id, "cover_photo" => User.banner_url(user) |> MediaProxy.url(), - "background_image" => image_url(user.info["background"]) |> MediaProxy.url(), + "background_image" => image_url(user.info.background) |> MediaProxy.url(), "is_local" => user.local, - "locked" => !!user.info["locked"], - "default_scope" => user.info["default_scope"] || "public", - "no_rich_text" => user.info["no_rich_text"] || false, - "fields" => fields + "locked" => user.info.locked, + "default_scope" => user.info.default_scope, + "no_rich_text" => user.info.no_rich_text, + "fields" => fields, + + # Pleroma extension + "pleroma" => %{ + "confirmation_pending" => user_info.confirmation_pending, + "tags" => user.tags + } } if assigns[:token] do - Map.put(data, "token", assigns[:token]) + Map.put(data, "token", token_string(assigns[:token])) else data end @@ -106,4 +116,7 @@ defmodule Pleroma.Web.TwitterAPI.UserView do defp image_url(%{"url" => [%{"href" => href} | _]}), do: href defp image_url(_), do: nil + + defp token_string(%Pleroma.Web.OAuth.Token{token: token_str}), do: token_str + defp token_string(token), do: token end diff --git a/lib/pleroma/web/twitter_api/views/util_view.ex b/lib/pleroma/web/twitter_api/views/util_view.ex index 71b04e6cc..aa5f842ac 100644 --- a/lib/pleroma/web/twitter_api/views/util_view.ex +++ b/lib/pleroma/web/twitter_api/views/util_view.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.TwitterAPI.UtilView do use Pleroma.Web, :view import Phoenix.HTML.Form diff --git a/lib/pleroma/web/views/error_helpers.ex b/lib/pleroma/web/views/error_helpers.ex index 3981b270d..df1e0d437 100644 --- a/lib/pleroma/web/views/error_helpers.ex +++ b/lib/pleroma/web/views/error_helpers.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.ErrorHelpers do @moduledoc """ Conveniences for translating and building error messages. diff --git a/lib/pleroma/web/views/error_view.ex b/lib/pleroma/web/views/error_view.ex index 7106031ae..d8158edb4 100644 --- a/lib/pleroma/web/views/error_view.ex +++ b/lib/pleroma/web/views/error_view.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.ErrorView do use Pleroma.Web, :view diff --git a/lib/pleroma/web/views/layout_view.ex b/lib/pleroma/web/views/layout_view.ex index d4d4c3bd3..ba94b9def 100644 --- a/lib/pleroma/web/views/layout_view.ex +++ b/lib/pleroma/web/views/layout_view.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.LayoutView do use Pleroma.Web, :view end diff --git a/lib/pleroma/web/web.ex b/lib/pleroma/web/web.ex index b82242a78..1aa86f645 100644 --- a/lib/pleroma/web/web.ex +++ b/lib/pleroma/web/web.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web do @moduledoc """ A module that keeps using definitions for controllers, diff --git a/lib/pleroma/web/web_finger/web_finger.ex b/lib/pleroma/web/web_finger/web_finger.ex index 9f554d286..3cc90d5dd 100644 --- a/lib/pleroma/web/web_finger/web_finger.ex +++ b/lib/pleroma/web/web_finger/web_finger.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.WebFinger do @httpoison Application.get_env(:pleroma, :httpoison) @@ -45,7 +49,7 @@ defmodule Pleroma.Web.WebFinger do def represent_user(user, "JSON") do {:ok, user} = ensure_keys_present(user) - {:ok, _private, public} = Salmon.keys_from_pem(user.info["keys"]) + {:ok, _private, public} = Salmon.keys_from_pem(user.info.keys) magic_key = Salmon.encode_key(public) %{ @@ -83,7 +87,7 @@ defmodule Pleroma.Web.WebFinger do def represent_user(user, "XML") do {:ok, user} = ensure_keys_present(user) - {:ok, _private, public} = Salmon.keys_from_pem(user.info["keys"]) + {:ok, _private, public} = Salmon.keys_from_pem(user.info.keys) magic_key = Salmon.encode_key(public) { @@ -113,16 +117,22 @@ defmodule Pleroma.Web.WebFinger do # This seems a better fit in Salmon def ensure_keys_present(user) do - info = user.info || %{} + info = user.info - if info["keys"] do + if info.keys do {:ok, user} else {:ok, pem} = Salmon.generate_rsa_pem() - info = Map.put(info, "keys", pem) - Ecto.Changeset.change(user, info: info) - |> User.update_and_set_cache() + info_cng = + info + |> Pleroma.User.Info.set_keys(pem) + + cng = + Ecto.Changeset.change(user) + |> Ecto.Changeset.put_embed(:info, info_cng) + + User.update_and_set_cache(cng) end end @@ -214,8 +224,8 @@ defmodule Pleroma.Web.WebFinger do end def find_lrdd_template(domain) do - with {:ok, %{status_code: status_code, body: body}} when status_code in 200..299 <- - @httpoison.get("http://#{domain}/.well-known/host-meta", [], follow_redirect: true) do + with {:ok, %{status: status, body: body}} when status in 200..299 <- + @httpoison.get("http://#{domain}/.well-known/host-meta", []) do get_template_from_xml(body) else _ -> @@ -250,10 +260,9 @@ defmodule Pleroma.Web.WebFinger do with response <- @httpoison.get( address, - [Accept: "application/xrd+xml,application/jrd+json"], - follow_redirect: true + Accept: "application/xrd+xml,application/jrd+json" ), - {:ok, %{status_code: status_code, body: body}} when status_code in 200..299 <- response do + {:ok, %{status: status, body: body}} when status in 200..299 <- response do doc = XML.parse_document(body) if doc != :error do diff --git a/lib/pleroma/web/web_finger/web_finger_controller.ex b/lib/pleroma/web/web_finger/web_finger_controller.ex index 002353166..66d5a880d 100644 --- a/lib/pleroma/web/web_finger/web_finger_controller.ex +++ b/lib/pleroma/web/web_finger/web_finger_controller.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.WebFinger.WebFingerController do use Pleroma.Web, :controller @@ -35,4 +39,8 @@ defmodule Pleroma.Web.WebFinger.WebFingerController do send_resp(conn, 404, "Unsupported format") end end + + def webfinger(conn, _params) do + send_resp(conn, 400, "Bad Request") + end end diff --git a/lib/pleroma/web/websub/websub.ex b/lib/pleroma/web/websub/websub.ex index 396dcf045..628ec38c5 100644 --- a/lib/pleroma/web/websub/websub.ex +++ b/lib/pleroma/web/websub/websub.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.Websub do alias Ecto.Changeset alias Pleroma.Repo @@ -146,7 +150,7 @@ defmodule Pleroma.Web.Websub do end def subscribe(subscriber, subscribed, requester \\ &request_subscription/1) do - topic = subscribed.info["topic"] + topic = subscribed.info.topic # FIXME: Race condition, use transactions {:ok, subscription} = with subscription when not is_nil(subscription) <- @@ -158,7 +162,7 @@ defmodule Pleroma.Web.Websub do _e -> subscription = %WebsubClientSubscription{ topic: topic, - hub: subscribed.info["hub"], + hub: subscribed.info.hub, subscribers: [subscriber.ap_id], state: "requested", secret: :crypto.strong_rand_bytes(8) |> Base.url_encode64(), @@ -173,7 +177,7 @@ defmodule Pleroma.Web.Websub do def gather_feed_data(topic, getter \\ &@httpoison.get/1) do with {:ok, response} <- getter.(topic), - status_code when status_code in 200..299 <- response.status_code, + status when status in 200..299 <- response.status, body <- response.body, doc <- XML.parse_document(body), uri when not is_nil(uri) <- XML.string_from_xpath("/feed/author[1]/uri", doc), @@ -221,7 +225,7 @@ defmodule Pleroma.Web.Websub do task = Task.async(websub_checker) - with {:ok, %{status_code: 202}} <- + with {:ok, %{status: 202}} <- poster.(websub.hub, {:form, data}, "Content-type": "application/x-www-form-urlencoded"), {:ok, websub} <- Task.yield(task, timeout) do {:ok, websub} @@ -257,17 +261,14 @@ defmodule Pleroma.Web.Websub do signature = sign(secret || "", xml) Logger.info(fn -> "Pushing #{topic} to #{callback}" end) - with {:ok, %{status_code: code}} <- + with {:ok, %{status: code}} <- @httpoison.post( callback, xml, [ {"Content-Type", "application/atom+xml"}, {"X-Hub-Signature", "sha1=#{signature}"} - ], - timeout: 10000, - recv_timeout: 20000, - hackney: [pool: :default] + ] ) do Logger.info(fn -> "Pushed to #{callback}, code #{code}" end) {:ok, code} diff --git a/lib/pleroma/web/websub/websub_client_subscription.ex b/lib/pleroma/web/websub/websub_client_subscription.ex index 8cea02939..2f511cd5b 100644 --- a/lib/pleroma/web/websub/websub_client_subscription.ex +++ b/lib/pleroma/web/websub/websub_client_subscription.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.Websub.WebsubClientSubscription do use Ecto.Schema alias Pleroma.User diff --git a/lib/pleroma/web/websub/websub_controller.ex b/lib/pleroma/web/websub/websub_controller.ex index c1934ba92..c38a03808 100644 --- a/lib/pleroma/web/websub/websub_controller.ex +++ b/lib/pleroma/web/websub/websub_controller.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.Websub.WebsubController do use Pleroma.Web, :controller alias Pleroma.{Repo, User} diff --git a/lib/pleroma/web/websub/websub_server_subscription.ex b/lib/pleroma/web/websub/websub_server_subscription.ex index 0e5248a73..81a2d7f07 100644 --- a/lib/pleroma/web/websub/websub_server_subscription.ex +++ b/lib/pleroma/web/websub/websub_server_subscription.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.Websub.WebsubServerSubscription do use Ecto.Schema diff --git a/lib/pleroma/web/xml/xml.ex b/lib/pleroma/web/xml/xml.ex index da3f68ecb..fa6dcd424 100644 --- a/lib/pleroma/web/xml/xml.ex +++ b/lib/pleroma/web/xml/xml.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Web.XML do require Logger @@ -25,15 +29,15 @@ defmodule Pleroma.Web.XML do {doc, _rest} = text |> :binary.bin_to_list() - |> :xmerl_scan.string() + |> :xmerl_scan.string(quiet: true) doc - catch - :exit, _error -> + rescue + _e -> Logger.debug("Couldn't parse XML: #{inspect(text)}") :error - rescue - e -> + catch + :exit, _error -> Logger.debug("Couldn't parse XML: #{inspect(text)}") :error end |