aboutsummaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authorMark Felder <feld@FreeBSD.org>2020-01-26 11:23:05 -0600
committerMark Felder <feld@FreeBSD.org>2020-01-26 11:23:05 -0600
commitd770cffce0aec0eeb427c8851437f04329700da9 (patch)
tree8a6f4db2849e613e0be968d3c0edc605b7040563 /lib
parent108a39c8766402dcbd0235d8746e2100a18e5813 (diff)
parentd9e2bd8f40b7d77713a72ef94da2fbe8ffa75b91 (diff)
downloadpleroma-d770cffce0aec0eeb427c8851437f04329700da9.tar.gz
Merge branch 'develop' into issue/1280
Diffstat (limited to 'lib')
-rw-r--r--lib/mix/tasks/pleroma/config.ex158
-rw-r--r--lib/mix/tasks/pleroma/docs.ex2
-rw-r--r--lib/pleroma/activity.ex7
-rw-r--r--lib/pleroma/activity/queries.ex10
-rw-r--r--lib/pleroma/activity/search.ex11
-rw-r--r--lib/pleroma/application.ex1
-rw-r--r--lib/pleroma/config/config_db.ex414
-rw-r--r--lib/pleroma/config/holder.ex16
-rw-r--r--lib/pleroma/config/loader.ex59
-rw-r--r--lib/pleroma/config/transfer_task.ex121
-rw-r--r--lib/pleroma/docs/generator.ex128
-rw-r--r--lib/pleroma/docs/json.ex20
-rw-r--r--lib/pleroma/notification.ex4
-rw-r--r--lib/pleroma/object.ex80
-rw-r--r--lib/pleroma/object/fetcher.ex3
-rw-r--r--lib/pleroma/repo.ex35
-rw-r--r--lib/pleroma/web/activity_pub/activity_pub.ex4
-rw-r--r--lib/pleroma/web/activity_pub/mrf/media_proxy_warming_policy.ex (renamed from lib/pleroma/web/activity_pub/mrf/mediaproxy_warming_policy.ex)0
-rw-r--r--lib/pleroma/web/activity_pub/mrf/no_op_policy.ex (renamed from lib/pleroma/web/activity_pub/mrf/noop_policy.ex)0
-rw-r--r--lib/pleroma/web/activity_pub/mrf/user_allow_list_policy.ex (renamed from lib/pleroma/web/activity_pub/mrf/user_allowlist_policy.ex)0
-rw-r--r--lib/pleroma/web/activity_pub/mrf/vocabulary_policy.ex2
-rw-r--r--lib/pleroma/web/activity_pub/transmogrifier.ex18
-rw-r--r--lib/pleroma/web/activity_pub/utils.ex72
-rw-r--r--lib/pleroma/web/admin_api/admin_api_controller.ex163
-rw-r--r--lib/pleroma/web/admin_api/config.ex182
-rw-r--r--lib/pleroma/web/admin_api/views/config_view.ex10
-rw-r--r--lib/pleroma/web/common_api/common_api.ex16
-rw-r--r--lib/pleroma/web/mastodon_api/controllers/search_controller.ex2
-rw-r--r--lib/pleroma/web/mastodon_api/controllers/subscription_controller.ex2
-rw-r--r--lib/pleroma/web/mastodon_api/controllers/timeline_controller.ex14
-rw-r--r--lib/pleroma/web/mastodon_api/views/notification_view.ex31
-rw-r--r--lib/pleroma/web/mastodon_api/views/status_view.ex12
-rw-r--r--lib/pleroma/web/oauth/oauth_controller.ex2
-rw-r--r--lib/pleroma/web/pleroma_api/controllers/pleroma_api_controller.ex17
-rw-r--r--lib/pleroma/web/router.ex2
-rw-r--r--lib/pleroma/workers/attachments_cleanup_worker.ex88
36 files changed, 1210 insertions, 496 deletions
diff --git a/lib/mix/tasks/pleroma/config.ex b/lib/mix/tasks/pleroma/config.ex
index 590c7a914..3e76d2c97 100644
--- a/lib/mix/tasks/pleroma/config.ex
+++ b/lib/mix/tasks/pleroma/config.ex
@@ -4,71 +4,147 @@
defmodule Mix.Tasks.Pleroma.Config do
use Mix.Task
+
import Mix.Pleroma
+
+ alias Pleroma.ConfigDB
alias Pleroma.Repo
- alias Pleroma.Web.AdminAPI.Config
+
@shortdoc "Manages the location of the config"
@moduledoc File.read!("docs/administration/CLI_tasks/config.md")
+
def run(["migrate_to_db"]) do
start_pleroma()
+ migrate_to_db()
+ end
+
+ def run(["migrate_from_db" | options]) do
+ start_pleroma()
- if Pleroma.Config.get([:instance, :dynamic_configuration]) do
- Application.get_all_env(:pleroma)
- |> Enum.reject(fn {k, _v} -> k in [Pleroma.Repo, :env] end)
- |> Enum.each(fn {k, v} ->
- key = to_string(k) |> String.replace("Elixir.", "")
+ {opts, _} =
+ OptionParser.parse!(options,
+ strict: [env: :string, delete: :boolean],
+ aliases: [d: :delete]
+ )
+
+ migrate_from_db(opts)
+ end
- key =
- if String.starts_with?(key, "Pleroma.") do
- key
+ @spec migrate_to_db(Path.t() | nil) :: any()
+ def migrate_to_db(file_path \\ nil) do
+ if Pleroma.Config.get([:configurable_from_database]) do
+ config_file =
+ if file_path do
+ file_path
+ else
+ if Pleroma.Config.get(:release) do
+ Pleroma.Config.get(:config_path)
else
- ":" <> key
+ "config/#{Pleroma.Config.get(:env)}.secret.exs"
end
+ end
- {:ok, _} = Config.update_or_create(%{group: "pleroma", key: key, value: v})
- Mix.shell().info("#{key} is migrated.")
- end)
-
- Mix.shell().info("Settings migrated.")
+ do_migrate_to_db(config_file)
else
- Mix.shell().info(
- "Migration is not allowed by config. You can change this behavior in instance settings."
- )
+ migration_error()
end
end
- def run(["migrate_from_db", env, delete?]) do
- start_pleroma()
+ defp do_migrate_to_db(config_file) do
+ if File.exists?(config_file) do
+ Ecto.Adapters.SQL.query!(Repo, "TRUNCATE config;")
+ Ecto.Adapters.SQL.query!(Repo, "ALTER SEQUENCE config_id_seq RESTART;")
- delete? = if delete? == "true", do: true, else: false
+ custom_config =
+ config_file
+ |> read_file()
+ |> elem(0)
- if Pleroma.Config.get([:instance, :dynamic_configuration]) do
- config_path = "config/#{env}.exported_from_db.secret.exs"
+ custom_config
+ |> Keyword.keys()
+ |> Enum.each(&create(&1, custom_config))
+ else
+ shell_info("To migrate settings, you must define custom settings in #{config_file}.")
+ end
+ end
- {:ok, file} = File.open(config_path, [:write, :utf8])
- IO.write(file, "use Mix.Config\r\n")
+ defp create(group, settings) do
+ group
+ |> Pleroma.Config.Loader.filter_group(settings)
+ |> Enum.each(fn {key, value} ->
+ key = inspect(key)
+ {:ok, _} = ConfigDB.update_or_create(%{group: inspect(group), key: key, value: value})
- Repo.all(Config)
- |> Enum.each(fn config ->
- IO.write(
- file,
- "config :#{config.group}, #{config.key}, #{
- inspect(Config.from_binary(config.value), limit: :infinity)
- }\r\n\r\n"
- )
+ shell_info("Settings for key #{key} migrated.")
+ end)
+
+ shell_info("Settings for group :#{group} migrated.")
+ end
- if delete? do
- {:ok, _} = Repo.delete(config)
- Mix.shell().info("#{config.key} deleted from DB.")
+ defp migrate_from_db(opts) do
+ if Pleroma.Config.get([:configurable_from_database]) do
+ env = opts[:env] || "prod"
+
+ config_path =
+ if Pleroma.Config.get(:release) do
+ :config_path
+ |> Pleroma.Config.get()
+ |> Path.dirname()
+ else
+ "config"
end
- end)
+ |> Path.join("#{env}.exported_from_db.secret.exs")
+
+ file = File.open!(config_path, [:write, :utf8])
+
+ IO.write(file, config_header())
- File.close(file)
+ ConfigDB
+ |> Repo.all()
+ |> Enum.each(&write_and_delete(&1, file, opts[:delete]))
+
+ :ok = File.close(file)
System.cmd("mix", ["format", config_path])
else
- Mix.shell().info(
- "Migration is not allowed by config. You can change this behavior in instance settings."
- )
+ migration_error()
end
end
+
+ defp migration_error do
+ shell_error(
+ "Migration is not allowed in config. You can change this behavior by setting `configurable_from_database` to true."
+ )
+ end
+
+ if Code.ensure_loaded?(Config.Reader) do
+ defp config_header, do: "import Config\r\n\r\n"
+ defp read_file(config_file), do: Config.Reader.read_imports!(config_file)
+ else
+ defp config_header, do: "use Mix.Config\r\n\r\n"
+ defp read_file(config_file), do: Mix.Config.eval!(config_file)
+ end
+
+ defp write_and_delete(config, file, delete?) do
+ config
+ |> write(file)
+ |> delete(delete?)
+ end
+
+ defp write(config, file) do
+ value =
+ config.value
+ |> ConfigDB.from_binary()
+ |> inspect(limit: :infinity)
+
+ IO.write(file, "config #{config.group}, #{config.key}, #{value}\r\n\r\n")
+
+ config
+ end
+
+ defp delete(config, true) do
+ {:ok, _} = Repo.delete(config)
+ shell_info("#{config.key} deleted from DB.")
+ end
+
+ defp delete(_config, _), do: :ok
end
diff --git a/lib/mix/tasks/pleroma/docs.ex b/lib/mix/tasks/pleroma/docs.ex
index 0d2663648..3c870f876 100644
--- a/lib/mix/tasks/pleroma/docs.ex
+++ b/lib/mix/tasks/pleroma/docs.ex
@@ -28,7 +28,7 @@ defmodule Mix.Tasks.Pleroma.Docs do
defp do_run(implementation) do
start_pleroma()
- with {descriptions, _paths} <- Mix.Config.eval!("config/description.exs"),
+ with descriptions <- Pleroma.Config.Loader.load("config/description.exs"),
{:ok, file_path} <-
Pleroma.Docs.Generator.process(
implementation,
diff --git a/lib/pleroma/activity.ex b/lib/pleroma/activity.ex
index 510d3273c..0f8fce774 100644
--- a/lib/pleroma/activity.ex
+++ b/lib/pleroma/activity.ex
@@ -30,7 +30,8 @@ defmodule Pleroma.Activity do
"Follow" => "follow",
"Announce" => "reblog",
"Like" => "favourite",
- "Move" => "move"
+ "Move" => "move",
+ "EmojiReaction" => "pleroma:emoji_reaction"
}
@mastodon_to_ap_notification_types for {k, v} <- @mastodon_notification_types,
@@ -312,9 +313,7 @@ defmodule Pleroma.Activity do
from(u in User.Query.build(deactivated: true), select: u.ap_id)
|> Repo.all()
- from(activity in query,
- where: activity.actor not in ^deactivated_users
- )
+ Activity.Queries.exclude_authors(query, deactivated_users)
end
defdelegate search(user, query, options \\ []), to: Pleroma.Activity.Search
diff --git a/lib/pleroma/activity/queries.ex b/lib/pleroma/activity/queries.ex
index 26bc1099d..79f305201 100644
--- a/lib/pleroma/activity/queries.ex
+++ b/lib/pleroma/activity/queries.ex
@@ -12,6 +12,7 @@ defmodule Pleroma.Activity.Queries do
@type query :: Ecto.Queryable.t() | Activity.t()
alias Pleroma.Activity
+ alias Pleroma.User
@spec by_ap_id(query, String.t()) :: query
def by_ap_id(query \\ Activity, ap_id) do
@@ -29,6 +30,11 @@ defmodule Pleroma.Activity.Queries do
)
end
+ @spec by_author(query, String.t()) :: query
+ def by_author(query \\ Activity, %User{ap_id: ap_id}) do
+ from(a in query, where: a.actor == ^ap_id)
+ end
+
@spec by_object_id(query, String.t() | [String.t()]) :: query
def by_object_id(query \\ Activity, object_id)
@@ -72,4 +78,8 @@ defmodule Pleroma.Activity.Queries do
where: fragment("(?)->>'type' != ?", activity.data, ^activity_type)
)
end
+
+ def exclude_authors(query \\ Activity, actors) do
+ from(activity in query, where: activity.actor not in ^actors)
+ end
end
diff --git a/lib/pleroma/activity/search.ex b/lib/pleroma/activity/search.ex
index d30a5a6a5..f96e208da 100644
--- a/lib/pleroma/activity/search.ex
+++ b/lib/pleroma/activity/search.ex
@@ -26,18 +26,23 @@ defmodule Pleroma.Activity.Search do
|> query_with(index_type, search_query)
|> maybe_restrict_local(user)
|> maybe_restrict_author(author)
+ |> maybe_restrict_blocked(user)
|> Pagination.fetch_paginated(%{"offset" => offset, "limit" => limit}, :offset)
|> maybe_fetch(user, search_query)
end
def maybe_restrict_author(query, %User{} = author) do
- from([a, o] in query,
- where: a.actor == ^author.ap_id
- )
+ Activity.Queries.by_author(query, author)
end
def maybe_restrict_author(query, _), do: query
+ def maybe_restrict_blocked(query, %User{} = user) do
+ Activity.Queries.exclude_authors(query, User.blocked_users_ap_ids(user))
+ end
+
+ def maybe_restrict_blocked(query, _), do: query
+
defp restrict_public(q) do
from([a, o] in q,
where: fragment("?->>'type' = 'Create'", a.data),
diff --git a/lib/pleroma/application.ex b/lib/pleroma/application.ex
index 2ae052069..e17068876 100644
--- a/lib/pleroma/application.ex
+++ b/lib/pleroma/application.ex
@@ -33,6 +33,7 @@ defmodule Pleroma.Application do
def start(_type, _args) do
Pleroma.HTML.compile_scrubbers()
Pleroma.Config.DeprecationWarnings.warn()
+ Pleroma.Repo.check_migrations_applied!()
setup_instrumenters()
load_custom_modules()
diff --git a/lib/pleroma/config/config_db.ex b/lib/pleroma/config/config_db.ex
new file mode 100644
index 000000000..119251bee
--- /dev/null
+++ b/lib/pleroma/config/config_db.ex
@@ -0,0 +1,414 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.ConfigDB do
+ use Ecto.Schema
+
+ import Ecto.Changeset
+ import Ecto.Query
+ import Pleroma.Web.Gettext
+
+ alias __MODULE__
+ alias Pleroma.Repo
+
+ @type t :: %__MODULE__{}
+
+ @full_key_update [
+ {:pleroma, :ecto_repos},
+ {:quack, :meta},
+ {:mime, :types},
+ {:cors_plug, [:max_age, :methods, :expose, :headers]},
+ {:auto_linker, :opts},
+ {:swarm, :node_blacklist},
+ {:logger, :backends}
+ ]
+
+ @full_subkey_update [
+ {:pleroma, :assets, :mascots},
+ {:pleroma, :emoji, :groups},
+ {:pleroma, :workers, :retries},
+ {:pleroma, :mrf_subchain, :match_actor},
+ {:pleroma, :mrf_keyword, :replace}
+ ]
+
+ @regex ~r/^~r(?'delimiter'[\/|"'([{<]{1})(?'pattern'.+)[\/|"')\]}>]{1}(?'modifier'[uismxfU]*)/u
+
+ @delimiters ["/", "|", "\"", "'", {"(", ")"}, {"[", "]"}, {"{", "}"}, {"<", ">"}]
+
+ schema "config" do
+ field(:key, :string)
+ field(:group, :string)
+ field(:value, :binary)
+ field(:db, {:array, :string}, virtual: true, default: [])
+
+ timestamps()
+ end
+
+ @spec get_all_as_keyword() :: keyword()
+ def get_all_as_keyword do
+ ConfigDB
+ |> select([c], {c.group, c.key, c.value})
+ |> Repo.all()
+ |> Enum.reduce([], fn {group, key, value}, acc ->
+ group = ConfigDB.from_string(group)
+ key = ConfigDB.from_string(key)
+ value = from_binary(value)
+
+ Keyword.update(acc, group, [{key, value}], &Keyword.merge(&1, [{key, value}]))
+ end)
+ end
+
+ @spec get_by_params(map()) :: ConfigDB.t() | nil
+ def get_by_params(params), do: Repo.get_by(ConfigDB, params)
+
+ @spec changeset(ConfigDB.t(), map()) :: Changeset.t()
+ def changeset(config, params \\ %{}) do
+ params = Map.put(params, :value, transform(params[:value]))
+
+ config
+ |> cast(params, [:key, :group, :value])
+ |> validate_required([:key, :group, :value])
+ |> unique_constraint(:key, name: :config_group_key_index)
+ end
+
+ @spec create(map()) :: {:ok, ConfigDB.t()} | {:error, Changeset.t()}
+ def create(params) do
+ %ConfigDB{}
+ |> changeset(params)
+ |> Repo.insert()
+ end
+
+ @spec update(ConfigDB.t(), map()) :: {:ok, ConfigDB.t()} | {:error, Changeset.t()}
+ def update(%ConfigDB{} = config, %{value: value}) do
+ config
+ |> changeset(%{value: value})
+ |> Repo.update()
+ end
+
+ @spec get_db_keys(ConfigDB.t()) :: [String.t()]
+ def get_db_keys(%ConfigDB{} = config) do
+ config.value
+ |> ConfigDB.from_binary()
+ |> get_db_keys(config.key)
+ end
+
+ @spec get_db_keys(keyword(), any()) :: [String.t()]
+ def get_db_keys(value, key) do
+ if Keyword.keyword?(value) do
+ value |> Keyword.keys() |> Enum.map(&convert(&1))
+ else
+ [convert(key)]
+ end
+ end
+
+ @spec merge_group(atom(), atom(), keyword(), keyword()) :: keyword()
+ def merge_group(group, key, old_value, new_value) do
+ new_keys = to_map_set(new_value)
+
+ intersect_keys =
+ old_value |> to_map_set() |> MapSet.intersection(new_keys) |> MapSet.to_list()
+
+ merged_value = ConfigDB.merge(old_value, new_value)
+
+ @full_subkey_update
+ |> Enum.map(fn
+ {g, k, subkey} when g == group and k == key ->
+ if subkey in intersect_keys, do: subkey, else: []
+
+ _ ->
+ []
+ end)
+ |> List.flatten()
+ |> Enum.reduce(merged_value, fn subkey, acc ->
+ Keyword.put(acc, subkey, new_value[subkey])
+ end)
+ end
+
+ defp to_map_set(keyword) do
+ keyword
+ |> Keyword.keys()
+ |> MapSet.new()
+ end
+
+ @spec sub_key_full_update?(atom(), atom(), [Keyword.key()]) :: boolean()
+ def sub_key_full_update?(group, key, subkeys) do
+ Enum.any?(@full_subkey_update, fn {g, k, subkey} ->
+ g == group and k == key and subkey in subkeys
+ end)
+ end
+
+ @spec merge(keyword(), keyword()) :: keyword()
+ def merge(config1, config2) when is_list(config1) and is_list(config2) do
+ Keyword.merge(config1, config2, fn _, app1, app2 ->
+ if Keyword.keyword?(app1) and Keyword.keyword?(app2) do
+ Keyword.merge(app1, app2, &deep_merge/3)
+ else
+ app2
+ end
+ end)
+ end
+
+ defp deep_merge(_key, value1, value2) do
+ if Keyword.keyword?(value1) and Keyword.keyword?(value2) do
+ Keyword.merge(value1, value2, &deep_merge/3)
+ else
+ value2
+ end
+ end
+
+ @spec update_or_create(map()) :: {:ok, ConfigDB.t()} | {:error, Changeset.t()}
+ def update_or_create(params) do
+ search_opts = Map.take(params, [:group, :key])
+
+ with %ConfigDB{} = config <- ConfigDB.get_by_params(search_opts),
+ {:partial_update, true, config} <-
+ {:partial_update, can_be_partially_updated?(config), config},
+ old_value <- from_binary(config.value),
+ transformed_value <- do_transform(params[:value]),
+ {:can_be_merged, true, config} <- {:can_be_merged, is_list(transformed_value), config},
+ new_value <-
+ merge_group(
+ ConfigDB.from_string(config.group),
+ ConfigDB.from_string(config.key),
+ old_value,
+ transformed_value
+ ) do
+ ConfigDB.update(config, %{value: new_value})
+ else
+ {reason, false, config} when reason in [:partial_update, :can_be_merged] ->
+ ConfigDB.update(config, params)
+
+ nil ->
+ ConfigDB.create(params)
+ end
+ end
+
+ defp can_be_partially_updated?(%ConfigDB{} = config), do: not only_full_update?(config)
+
+ defp only_full_update?(%ConfigDB{} = config) do
+ config_group = ConfigDB.from_string(config.group)
+ config_key = ConfigDB.from_string(config.key)
+
+ Enum.any?(@full_key_update, fn
+ {group, key} when is_list(key) ->
+ config_group == group and config_key in key
+
+ {group, key} ->
+ config_group == group and config_key == key
+ end)
+ end
+
+ @spec delete(map()) :: {:ok, ConfigDB.t()} | {:error, Changeset.t()}
+ def delete(params) do
+ search_opts = Map.delete(params, :subkeys)
+
+ with %ConfigDB{} = config <- ConfigDB.get_by_params(search_opts),
+ {config, sub_keys} when is_list(sub_keys) <- {config, params[:subkeys]},
+ old_value <- from_binary(config.value),
+ keys <- Enum.map(sub_keys, &do_transform_string(&1)),
+ {:partial_remove, config, new_value} when new_value != [] <-
+ {:partial_remove, config, Keyword.drop(old_value, keys)} do
+ ConfigDB.update(config, %{value: new_value})
+ else
+ {:partial_remove, config, []} ->
+ Repo.delete(config)
+
+ {config, nil} ->
+ Repo.delete(config)
+
+ nil ->
+ err =
+ dgettext("errors", "Config with params %{params} not found", params: inspect(params))
+
+ {:error, err}
+ end
+ end
+
+ @spec from_binary(binary()) :: term()
+ def from_binary(binary), do: :erlang.binary_to_term(binary)
+
+ @spec from_binary_with_convert(binary()) :: any()
+ def from_binary_with_convert(binary) do
+ binary
+ |> from_binary()
+ |> do_convert()
+ end
+
+ @spec from_string(String.t()) :: atom() | no_return()
+ def from_string(string), do: do_transform_string(string)
+
+ @spec convert(any()) :: any()
+ def convert(entity), do: do_convert(entity)
+
+ defp do_convert(entity) when is_list(entity) do
+ for v <- entity, into: [], do: do_convert(v)
+ end
+
+ defp do_convert(%Regex{} = entity), do: inspect(entity)
+
+ defp do_convert(entity) when is_map(entity) do
+ for {k, v} <- entity, into: %{}, do: {do_convert(k), do_convert(v)}
+ end
+
+ defp do_convert({:proxy_url, {type, :localhost, port}}) do
+ %{"tuple" => [":proxy_url", %{"tuple" => [do_convert(type), "localhost", port]}]}
+ end
+
+ defp do_convert({:proxy_url, {type, host, port}}) when is_tuple(host) do
+ ip =
+ host
+ |> :inet_parse.ntoa()
+ |> to_string()
+
+ %{
+ "tuple" => [
+ ":proxy_url",
+ %{"tuple" => [do_convert(type), ip, port]}
+ ]
+ }
+ end
+
+ defp do_convert({:proxy_url, {type, host, port}}) do
+ %{
+ "tuple" => [
+ ":proxy_url",
+ %{"tuple" => [do_convert(type), to_string(host), port]}
+ ]
+ }
+ end
+
+ defp do_convert({:partial_chain, entity}), do: %{"tuple" => [":partial_chain", inspect(entity)]}
+
+ defp do_convert(entity) when is_tuple(entity) do
+ value =
+ entity
+ |> Tuple.to_list()
+ |> do_convert()
+
+ %{"tuple" => value}
+ end
+
+ defp do_convert(entity) when is_boolean(entity) or is_number(entity) or is_nil(entity) do
+ entity
+ end
+
+ defp do_convert(entity)
+ when is_atom(entity) and entity in [:"tlsv1.1", :"tlsv1.2", :"tlsv1.3"] do
+ ":#{entity}"
+ end
+
+ defp do_convert(entity) when is_atom(entity), do: inspect(entity)
+
+ defp do_convert(entity) when is_binary(entity), do: entity
+
+ @spec transform(any()) :: binary() | no_return()
+ def transform(entity) when is_binary(entity) or is_map(entity) or is_list(entity) do
+ entity
+ |> do_transform()
+ |> to_binary()
+ end
+
+ def transform(entity), do: to_binary(entity)
+
+ @spec transform_with_out_binary(any()) :: any()
+ def transform_with_out_binary(entity), do: do_transform(entity)
+
+ @spec to_binary(any()) :: binary()
+ def to_binary(entity), do: :erlang.term_to_binary(entity)
+
+ defp do_transform(%Regex{} = entity), do: entity
+
+ defp do_transform(%{"tuple" => [":proxy_url", %{"tuple" => [type, host, port]}]}) do
+ {:proxy_url, {do_transform_string(type), parse_host(host), port}}
+ end
+
+ defp do_transform(%{"tuple" => [":partial_chain", entity]}) do
+ {partial_chain, []} =
+ entity
+ |> String.replace(~r/[^\w|^{:,[|^,|^[|^\]^}|^\/|^\.|^"]^\s/, "")
+ |> Code.eval_string()
+
+ {:partial_chain, partial_chain}
+ end
+
+ defp do_transform(%{"tuple" => entity}) do
+ Enum.reduce(entity, {}, fn val, acc -> Tuple.append(acc, do_transform(val)) end)
+ end
+
+ defp do_transform(entity) when is_map(entity) do
+ for {k, v} <- entity, into: %{}, do: {do_transform(k), do_transform(v)}
+ end
+
+ defp do_transform(entity) when is_list(entity) do
+ for v <- entity, into: [], do: do_transform(v)
+ end
+
+ defp do_transform(entity) when is_binary(entity) do
+ entity
+ |> String.trim()
+ |> do_transform_string()
+ end
+
+ defp do_transform(entity), do: entity
+
+ defp parse_host("localhost"), do: :localhost
+
+ defp parse_host(host) do
+ charlist = to_charlist(host)
+
+ case :inet.parse_address(charlist) do
+ {:error, :einval} ->
+ charlist
+
+ {:ok, ip} ->
+ ip
+ end
+ end
+
+ defp find_valid_delimiter([], _string, _) do
+ raise(ArgumentError, message: "valid delimiter for Regex expression not found")
+ end
+
+ defp find_valid_delimiter([{leading, closing} = delimiter | others], pattern, regex_delimiter)
+ when is_tuple(delimiter) do
+ if String.contains?(pattern, closing) do
+ find_valid_delimiter(others, pattern, regex_delimiter)
+ else
+ {:ok, {leading, closing}}
+ end
+ end
+
+ defp find_valid_delimiter([delimiter | others], pattern, regex_delimiter) do
+ if String.contains?(pattern, delimiter) do
+ find_valid_delimiter(others, pattern, regex_delimiter)
+ else
+ {:ok, {delimiter, delimiter}}
+ end
+ end
+
+ defp do_transform_string("~r" <> _pattern = regex) do
+ with %{"modifier" => modifier, "pattern" => pattern, "delimiter" => regex_delimiter} <-
+ Regex.named_captures(@regex, regex),
+ {:ok, {leading, closing}} <- find_valid_delimiter(@delimiters, pattern, regex_delimiter),
+ {result, _} <- Code.eval_string("~r#{leading}#{pattern}#{closing}#{modifier}") do
+ result
+ end
+ end
+
+ defp do_transform_string(":" <> atom), do: String.to_atom(atom)
+
+ defp do_transform_string(value) do
+ if is_module_name?(value) do
+ String.to_existing_atom("Elixir." <> value)
+ else
+ value
+ end
+ end
+
+ @spec is_module_name?(String.t()) :: boolean()
+ def is_module_name?(string) do
+ Regex.match?(~r/^(Pleroma|Phoenix|Tesla|Quack|Ueberauth|Swoosh)\./, string) or
+ string in ["Oban", "Ueberauth", "ExSyslogger"]
+ end
+end
diff --git a/lib/pleroma/config/holder.ex b/lib/pleroma/config/holder.ex
new file mode 100644
index 000000000..d4fe892af
--- /dev/null
+++ b/lib/pleroma/config/holder.ex
@@ -0,0 +1,16 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.Config.Holder do
+ @config Pleroma.Config.Loader.load_and_merge()
+
+ @spec config() :: keyword()
+ def config, do: @config
+
+ @spec config(atom()) :: any()
+ def config(group), do: @config[group]
+
+ @spec config(atom(), atom()) :: any()
+ def config(group, key), do: @config[group][key]
+end
diff --git a/lib/pleroma/config/loader.ex b/lib/pleroma/config/loader.ex
new file mode 100644
index 000000000..68b247381
--- /dev/null
+++ b/lib/pleroma/config/loader.ex
@@ -0,0 +1,59 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.Config.Loader do
+ @paths ["config/config.exs", "config/#{Mix.env()}.exs"]
+
+ @reject_keys [
+ Pleroma.Repo,
+ Pleroma.Web.Endpoint,
+ :env,
+ :configurable_from_database,
+ :database,
+ :swarm
+ ]
+
+ if Code.ensure_loaded?(Config.Reader) do
+ @spec load(Path.t()) :: keyword()
+ def load(path), do: Config.Reader.read!(path)
+
+ defp do_merge(conf1, conf2), do: Config.Reader.merge(conf1, conf2)
+ else
+ # support for Elixir less than 1.9
+ @spec load(Path.t()) :: keyword()
+ def load(path) do
+ path
+ |> Mix.Config.eval!()
+ |> elem(0)
+ end
+
+ defp do_merge(conf1, conf2), do: Mix.Config.merge(conf1, conf2)
+ end
+
+ @spec load_and_merge() :: keyword()
+ def load_and_merge do
+ all_paths =
+ if Pleroma.Config.get(:release),
+ do: @paths ++ ["config/releases.exs"],
+ else: @paths
+
+ all_paths
+ |> Enum.map(&load(&1))
+ |> Enum.reduce([], &do_merge(&2, &1))
+ |> filter()
+ end
+
+ defp filter(configs) do
+ configs
+ |> Keyword.keys()
+ |> Enum.reduce([], &Keyword.put(&2, &1, filter_group(&1, configs)))
+ end
+
+ @spec filter_group(atom(), keyword()) :: keyword()
+ def filter_group(group, configs) do
+ Enum.reject(configs[group], fn {key, _v} ->
+ key in @reject_keys or (group == :phoenix and key == :serve_endpoints)
+ end)
+ end
+end
diff --git a/lib/pleroma/config/transfer_task.ex b/lib/pleroma/config/transfer_task.ex
index 3214c9951..d54f38ee4 100644
--- a/lib/pleroma/config/transfer_task.ex
+++ b/lib/pleroma/config/transfer_task.ex
@@ -4,56 +4,111 @@
defmodule Pleroma.Config.TransferTask do
use Task
- alias Pleroma.Web.AdminAPI.Config
+
+ alias Pleroma.ConfigDB
+ alias Pleroma.Repo
+
+ require Logger
def start_link(_) do
load_and_update_env()
- if Pleroma.Config.get(:env) == :test, do: Ecto.Adapters.SQL.Sandbox.checkin(Pleroma.Repo)
+ if Pleroma.Config.get(:env) == :test, do: Ecto.Adapters.SQL.Sandbox.checkin(Repo)
:ignore
end
- def load_and_update_env do
- if Pleroma.Config.get([:instance, :dynamic_configuration]) and
- Ecto.Adapters.SQL.table_exists?(Pleroma.Repo, "config") do
- for_restart =
- Pleroma.Repo.all(Config)
- |> Enum.map(&update_env(&1))
-
+ @spec load_and_update_env([ConfigDB.t()]) :: :ok | false
+ def load_and_update_env(deleted \\ []) do
+ with true <- Pleroma.Config.get(:configurable_from_database),
+ true <- Ecto.Adapters.SQL.table_exists?(Repo, "config"),
+ started_applications <- Application.started_applications() do
# We need to restart applications for loaded settings take effect
- for_restart
- |> Enum.reject(&(&1 in [:pleroma, :ok]))
- |> Enum.each(fn app ->
- Application.stop(app)
- :ok = Application.start(app)
- end)
+ in_db = Repo.all(ConfigDB)
+
+ with_deleted = in_db ++ deleted
+
+ with_deleted
+ |> Enum.map(&merge_and_update(&1))
+ |> Enum.uniq()
+ # TODO: some problem with prometheus after restart!
+ |> Enum.reject(&(&1 in [:pleroma, nil, :prometheus]))
+ |> Enum.each(&restart(started_applications, &1))
+
+ :ok
end
end
- defp update_env(setting) do
+ defp merge_and_update(setting) do
try do
- key =
- if String.starts_with?(setting.key, "Pleroma.") do
- "Elixir." <> setting.key
+ key = ConfigDB.from_string(setting.key)
+ group = ConfigDB.from_string(setting.group)
+
+ default = Pleroma.Config.Holder.config(group, key)
+ merged_value = merge_value(setting, default, group, key)
+
+ :ok = update_env(group, key, merged_value)
+
+ if group != :logger do
+ group
+ else
+ # change logger configuration in runtime, without restart
+ if Keyword.keyword?(merged_value) and
+ key not in [:compile_time_application, :backends, :compile_time_purge_matching] do
+ Logger.configure_backend(key, merged_value)
else
- String.trim_leading(setting.key, ":")
+ Logger.configure([{key, merged_value}])
end
- group = String.to_existing_atom(setting.group)
+ nil
+ end
+ rescue
+ error ->
+ error_msg =
+ "updating env causes error, group: " <>
+ inspect(setting.group) <>
+ " key: " <>
+ inspect(setting.key) <>
+ " value: " <>
+ inspect(ConfigDB.from_binary(setting.value)) <> " error: " <> inspect(error)
- Application.put_env(
- group,
- String.to_existing_atom(key),
- Config.from_binary(setting.value)
- )
+ Logger.warn(error_msg)
- group
- rescue
- e ->
- require Logger
+ nil
+ end
+ end
+
+ defp merge_value(%{__meta__: %{state: :deleted}}, default, _group, _key), do: default
+
+ defp merge_value(setting, default, group, key) do
+ value = ConfigDB.from_binary(setting.value)
- Logger.warn(
- "updating env causes error, key: #{inspect(setting.key)}, error: #{inspect(e)}"
- )
+ if can_be_merged?(default, value) do
+ ConfigDB.merge_group(group, key, default, value)
+ else
+ value
end
end
+
+ defp update_env(group, key, nil), do: Application.delete_env(group, key)
+ defp update_env(group, key, value), do: Application.put_env(group, key, value)
+
+ defp restart(started_applications, app) do
+ with {^app, _, _} <- List.keyfind(started_applications, app, 0),
+ :ok <- Application.stop(app) do
+ :ok = Application.start(app)
+ else
+ nil ->
+ Logger.warn("#{app} is not started.")
+
+ error ->
+ error
+ |> inspect()
+ |> Logger.warn()
+ end
+ end
+
+ defp can_be_merged?(val1, val2) when is_list(val1) and is_list(val2) do
+ Keyword.keyword?(val1) and Keyword.keyword?(val2)
+ end
+
+ defp can_be_merged?(_val1, _val2), do: false
end
diff --git a/lib/pleroma/docs/generator.ex b/lib/pleroma/docs/generator.ex
index aa578eee2..6b12dcdd9 100644
--- a/lib/pleroma/docs/generator.ex
+++ b/lib/pleroma/docs/generator.ex
@@ -6,68 +6,116 @@ defmodule Pleroma.Docs.Generator do
implementation.process(descriptions)
end
- @spec uploaders_list() :: [module()]
- def uploaders_list do
- {:ok, modules} = :application.get_key(:pleroma, :modules)
+ @spec list_modules_in_dir(String.t(), String.t()) :: [module()]
+ def list_modules_in_dir(dir, start) do
+ with {:ok, files} <- File.ls(dir) do
+ files
+ |> Enum.filter(&String.ends_with?(&1, ".ex"))
+ |> Enum.map(fn filename ->
+ module = filename |> String.trim_trailing(".ex") |> Macro.camelize()
+ String.to_existing_atom(start <> module)
+ end)
+ end
+ end
+
+ @doc """
+ Converts:
+ - atoms to strings with leading `:`
+ - module names to strings, without leading `Elixir.`
+ - add humanized labels to `keys` if label is not defined, e.g. `:instance` -> `Instance`
+ """
+ @spec convert_to_strings([map()]) :: [map()]
+ def convert_to_strings(descriptions) do
+ Enum.map(descriptions, &format_entity(&1))
+ end
- Enum.filter(modules, fn module ->
- name_as_list = Module.split(module)
+ defp format_entity(entity) do
+ entity
+ |> format_key()
+ |> Map.put(:group, atom_to_string(entity[:group]))
+ |> format_children()
+ end
- List.starts_with?(name_as_list, ["Pleroma", "Uploaders"]) and
- List.last(name_as_list) != "Uploader"
- end)
+ defp format_key(%{key: key} = entity) do
+ entity
+ |> Map.put(:key, atom_to_string(key))
+ |> Map.put(:label, entity[:label] || humanize(key))
end
- @spec filters_list() :: [module()]
- def filters_list do
- {:ok, modules} = :application.get_key(:pleroma, :modules)
+ defp format_key(%{group: group} = entity) do
+ Map.put(entity, :label, entity[:label] || humanize(group))
+ end
- Enum.filter(modules, fn module ->
- name_as_list = Module.split(module)
+ defp format_key(entity), do: entity
- List.starts_with?(name_as_list, ["Pleroma", "Upload", "Filter"])
- end)
+ defp format_children(%{children: children} = entity) do
+ Map.put(entity, :children, Enum.map(children, &format_child(&1)))
end
- @spec mrf_list() :: [module()]
- def mrf_list do
- {:ok, modules} = :application.get_key(:pleroma, :modules)
+ defp format_children(entity), do: entity
+
+ defp format_child(%{suggestions: suggestions} = entity) do
+ entity
+ |> Map.put(:suggestions, format_suggestions(suggestions))
+ |> format_key()
+ |> format_group()
+ |> format_children()
+ end
- Enum.filter(modules, fn module ->
- name_as_list = Module.split(module)
+ defp format_child(entity) do
+ entity
+ |> format_key()
+ |> format_group()
+ |> format_children()
+ end
- List.starts_with?(name_as_list, ["Pleroma", "Web", "ActivityPub", "MRF"]) and
- length(name_as_list) > 4
- end)
+ defp format_group(%{group: group} = entity) do
+ Map.put(entity, :group, format_suggestion(group))
end
- @spec richmedia_parsers() :: [module()]
- def richmedia_parsers do
- {:ok, modules} = :application.get_key(:pleroma, :modules)
+ defp format_group(entity), do: entity
+
+ defp atom_to_string(entity) when is_binary(entity), do: entity
- Enum.filter(modules, fn module ->
- name_as_list = Module.split(module)
+ defp atom_to_string(entity) when is_atom(entity), do: inspect(entity)
- List.starts_with?(name_as_list, ["Pleroma", "Web", "RichMedia", "Parsers"]) and
- length(name_as_list) == 5
- end)
+ defp humanize(entity) do
+ string = inspect(entity)
+
+ if String.starts_with?(string, ":"),
+ do: Phoenix.Naming.humanize(entity),
+ else: string
end
+
+ defp format_suggestions([]), do: []
+
+ defp format_suggestions([suggestion | tail]) do
+ [format_suggestion(suggestion) | format_suggestions(tail)]
+ end
+
+ defp format_suggestion(entity) when is_atom(entity) do
+ atom_to_string(entity)
+ end
+
+ defp format_suggestion([head | tail] = entity) when is_list(entity) do
+ [format_suggestion(head) | format_suggestions(tail)]
+ end
+
+ defp format_suggestion(entity) when is_tuple(entity) do
+ format_suggestions(Tuple.to_list(entity)) |> List.to_tuple()
+ end
+
+ defp format_suggestion(entity), do: entity
end
defimpl Jason.Encoder, for: Tuple do
- def encode(tuple, opts) do
- Jason.Encode.list(Tuple.to_list(tuple), opts)
- end
+ def encode(tuple, opts), do: Jason.Encode.list(Tuple.to_list(tuple), opts)
end
defimpl Jason.Encoder, for: [Regex, Function] do
- def encode(term, opts) do
- Jason.Encode.string(inspect(term), opts)
- end
+ def encode(term, opts), do: Jason.Encode.string(inspect(term), opts)
end
defimpl String.Chars, for: Regex do
- def to_string(term) do
- inspect(term)
- end
+ def to_string(term), do: inspect(term)
end
diff --git a/lib/pleroma/docs/json.ex b/lib/pleroma/docs/json.ex
index f2a56d845..6508a7bdb 100644
--- a/lib/pleroma/docs/json.ex
+++ b/lib/pleroma/docs/json.ex
@@ -3,18 +3,22 @@ defmodule Pleroma.Docs.JSON do
@spec process(keyword()) :: {:ok, String.t()}
def process(descriptions) do
- config_path = "docs/generate_config.json"
-
- with {:ok, file} <- File.open(config_path, [:write, :utf8]),
- json <- generate_json(descriptions),
+ with path <- "docs/generated_config.json",
+ {:ok, file} <- File.open(path, [:write, :utf8]),
+ formatted_descriptions <-
+ Pleroma.Docs.Generator.convert_to_strings(descriptions),
+ json <- Jason.encode!(formatted_descriptions),
:ok <- IO.write(file, json),
:ok <- File.close(file) do
- {:ok, config_path}
+ {:ok, path}
end
end
- @spec generate_json([keyword()]) :: String.t()
- def generate_json(descriptions) do
- Jason.encode!(descriptions)
+ def compile do
+ with config <- Pleroma.Config.Loader.load("config/description.exs") do
+ config[:pleroma][:config_description]
+ |> Pleroma.Docs.Generator.convert_to_strings()
+ |> Jason.encode!()
+ end
end
end
diff --git a/lib/pleroma/notification.ex b/lib/pleroma/notification.ex
index 8f3e46af9..d04a65a1e 100644
--- a/lib/pleroma/notification.ex
+++ b/lib/pleroma/notification.ex
@@ -294,7 +294,7 @@ defmodule Pleroma.Notification do
end
def create_notifications(%Activity{data: %{"type" => type}} = activity)
- when type in ["Like", "Announce", "Follow", "Move"] do
+ when type in ["Like", "Announce", "Follow", "Move", "EmojiReaction"] do
notifications =
activity
|> get_notified_from_activity()
@@ -322,7 +322,7 @@ defmodule Pleroma.Notification do
def get_notified_from_activity(activity, local_only \\ true)
def get_notified_from_activity(%Activity{data: %{"type" => type}} = activity, local_only)
- when type in ["Create", "Like", "Announce", "Follow", "Move"] do
+ when type in ["Create", "Like", "Announce", "Follow", "Move", "EmojiReaction"] do
[]
|> Utils.maybe_notify_to_recipients(activity)
|> Utils.maybe_notify_mentioned_recipients(activity)
diff --git a/lib/pleroma/object.ex b/lib/pleroma/object.ex
index 2452a7389..38e372f6d 100644
--- a/lib/pleroma/object.ex
+++ b/lib/pleroma/object.ex
@@ -19,6 +19,8 @@ defmodule Pleroma.Object do
@type t() :: %__MODULE__{}
+ @derive {Jason.Encoder, only: [:data]}
+
schema "objects" do
field(:data, :map)
@@ -180,85 +182,17 @@ defmodule Pleroma.Object do
def delete(%Object{data: %{"id" => id}} = object) do
with {:ok, _obj} = swap_object_with_tombstone(object),
- :ok <- delete_attachments(object),
deleted_activity = Activity.delete_all_by_object_ap_id(id),
{:ok, true} <- Cachex.del(:object_cache, "object:#{id}"),
- {:ok, _} <- Cachex.del(:web_resp_cache, URI.parse(id).path) do
+ {:ok, _} <- Cachex.del(:web_resp_cache, URI.parse(id).path),
+ {:ok, _} <-
+ Pleroma.Workers.AttachmentsCleanupWorker.enqueue("cleanup_attachments", %{
+ "object" => object
+ }) do
{:ok, object, deleted_activity}
end
end
- defp delete_attachments(%{data: %{"attachment" => [_ | _] = attachments, "actor" => actor}}) do
- hrefs =
- Enum.flat_map(attachments, fn attachment ->
- Enum.map(attachment["url"], & &1["href"])
- end)
-
- names = Enum.map(attachments, & &1["name"])
-
- uploader = Pleroma.Config.get([Pleroma.Upload, :uploader])
-
- # find all objects for copies of the attachments, name and actor doesn't matter here
- delete_ids =
- from(o in Object,
- where:
- fragment(
- "to_jsonb(array(select jsonb_array_elements((?)#>'{url}') ->> 'href'))::jsonb \\?| (?)",
- o.data,
- ^hrefs
- )
- )
- |> Repo.all()
- # we should delete 1 object for any given attachment, but don't delete files if
- # there are more than 1 object for it
- |> Enum.reduce(%{}, fn %{
- id: id,
- data: %{
- "url" => [%{"href" => href}],
- "actor" => obj_actor,
- "name" => name
- }
- },
- acc ->
- Map.update(acc, href, %{id: id, count: 1}, fn val ->
- case obj_actor == actor and name in names do
- true ->
- # set id of the actor's object that will be deleted
- %{val | id: id, count: val.count + 1}
-
- false ->
- # another actor's object, just increase count to not delete file
- %{val | count: val.count + 1}
- end
- end)
- end)
- |> Enum.map(fn {href, %{id: id, count: count}} ->
- # only delete files that have single instance
- with 1 <- count do
- prefix =
- case Pleroma.Config.get([Pleroma.Upload, :base_url]) do
- nil -> "media"
- _ -> ""
- end
-
- base_url = Pleroma.Config.get([__MODULE__, :base_url], Pleroma.Web.base_url())
-
- file_path = String.trim_leading(href, "#{base_url}/#{prefix}")
-
- uploader.delete_file(file_path)
- end
-
- id
- end)
-
- from(o in Object, where: o.id in ^delete_ids)
- |> Repo.delete_all()
-
- :ok
- end
-
- defp delete_attachments(%{data: _data}), do: :ok
-
def prune(%Object{data: %{"id" => id}} = object) do
with {:ok, object} <- Repo.delete(object),
{:ok, true} <- Cachex.del(:object_cache, "object:#{id}"),
diff --git a/lib/pleroma/object/fetcher.ex b/lib/pleroma/object/fetcher.ex
index a1bde90f1..037c42339 100644
--- a/lib/pleroma/object/fetcher.ex
+++ b/lib/pleroma/object/fetcher.ex
@@ -117,6 +117,9 @@ defmodule Pleroma.Object.Fetcher do
{:error, %Tesla.Mock.Error{}} ->
nil
+ {:error, "Object has been deleted"} ->
+ nil
+
e ->
Logger.error("Error while fetching #{id}: #{inspect(e)}")
nil
diff --git a/lib/pleroma/repo.ex b/lib/pleroma/repo.ex
index f57e088bc..cb0b6653c 100644
--- a/lib/pleroma/repo.ex
+++ b/lib/pleroma/repo.ex
@@ -8,6 +8,8 @@ defmodule Pleroma.Repo do
adapter: Ecto.Adapters.Postgres,
migration_timestamps: [type: :naive_datetime_usec]
+ require Logger
+
defmodule Instrumenter do
use Prometheus.EctoInstrumenter
end
@@ -47,4 +49,37 @@ defmodule Pleroma.Repo do
_ -> {:error, :not_found}
end
end
+
+ def check_migrations_applied!() do
+ unless Pleroma.Config.get(
+ [:i_am_aware_this_may_cause_data_loss, :disable_migration_check],
+ false
+ ) do
+ Ecto.Migrator.with_repo(__MODULE__, fn repo ->
+ down_migrations =
+ Ecto.Migrator.migrations(repo)
+ |> Enum.reject(fn
+ {:up, _, _} -> true
+ {:down, _, _} -> false
+ end)
+
+ if length(down_migrations) > 0 do
+ down_migrations_text =
+ Enum.map(down_migrations, fn {:down, id, name} -> "- #{name} (#{id})\n" end)
+
+ Logger.error(
+ "The following migrations were not applied:\n#{down_migrations_text}If you want to start Pleroma anyway, set\nconfig :pleroma, :i_am_aware_this_may_cause_data_loss, disable_migration_check: true"
+ )
+
+ raise Pleroma.Repo.UnappliedMigrationsError
+ end
+ end)
+ else
+ :ok
+ end
+ end
+end
+
+defmodule Pleroma.Repo.UnappliedMigrationsError do
+ defexception message: "Unapplied Migrations detected"
end
diff --git a/lib/pleroma/web/activity_pub/activity_pub.ex b/lib/pleroma/web/activity_pub/activity_pub.ex
index 60c9e7e64..2e9d56ee5 100644
--- a/lib/pleroma/web/activity_pub/activity_pub.ex
+++ b/lib/pleroma/web/activity_pub/activity_pub.ex
@@ -1369,6 +1369,10 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do
data <- maybe_update_follow_information(data) do
{:ok, data}
else
+ {:error, "Object has been deleted"} = e ->
+ Logger.debug("Could not decode user at fetch #{ap_id}, #{inspect(e)}")
+ {:error, e}
+
e ->
Logger.error("Could not decode user at fetch #{ap_id}, #{inspect(e)}")
{:error, e}
diff --git a/lib/pleroma/web/activity_pub/mrf/mediaproxy_warming_policy.ex b/lib/pleroma/web/activity_pub/mrf/media_proxy_warming_policy.ex
index df774b0f7..df774b0f7 100644
--- a/lib/pleroma/web/activity_pub/mrf/mediaproxy_warming_policy.ex
+++ b/lib/pleroma/web/activity_pub/mrf/media_proxy_warming_policy.ex
diff --git a/lib/pleroma/web/activity_pub/mrf/noop_policy.ex b/lib/pleroma/web/activity_pub/mrf/no_op_policy.ex
index 878c57925..878c57925 100644
--- a/lib/pleroma/web/activity_pub/mrf/noop_policy.ex
+++ b/lib/pleroma/web/activity_pub/mrf/no_op_policy.ex
diff --git a/lib/pleroma/web/activity_pub/mrf/user_allowlist_policy.ex b/lib/pleroma/web/activity_pub/mrf/user_allow_list_policy.ex
index 7389d6a96..7389d6a96 100644
--- a/lib/pleroma/web/activity_pub/mrf/user_allowlist_policy.ex
+++ b/lib/pleroma/web/activity_pub/mrf/user_allow_list_policy.ex
diff --git a/lib/pleroma/web/activity_pub/mrf/vocabulary_policy.ex b/lib/pleroma/web/activity_pub/mrf/vocabulary_policy.ex
index 4eaea00d8..c184c3b66 100644
--- a/lib/pleroma/web/activity_pub/mrf/vocabulary_policy.ex
+++ b/lib/pleroma/web/activity_pub/mrf/vocabulary_policy.ex
@@ -20,7 +20,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.VocabularyPolicy do
with accepted_vocabulary <- Pleroma.Config.get([:mrf_vocabulary, :accept]),
rejected_vocabulary <- Pleroma.Config.get([:mrf_vocabulary, :reject]),
true <-
- length(accepted_vocabulary) == 0 || Enum.member?(accepted_vocabulary, message_type),
+ Enum.empty?(accepted_vocabulary) || Enum.member?(accepted_vocabulary, message_type),
false <-
length(rejected_vocabulary) > 0 && Enum.member?(rejected_vocabulary, message_type),
{:ok, _} <- filter(message["object"]) do
diff --git a/lib/pleroma/web/activity_pub/transmogrifier.ex b/lib/pleroma/web/activity_pub/transmogrifier.ex
index 3fa789d53..2b8bfc3bd 100644
--- a/lib/pleroma/web/activity_pub/transmogrifier.ex
+++ b/lib/pleroma/web/activity_pub/transmogrifier.ex
@@ -658,24 +658,8 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do
with %User{ap_id: ^actor_id} = actor <- User.get_cached_by_ap_id(object["id"]) do
{:ok, new_user_data} = ActivityPub.user_data_from_user_object(object)
- locked = new_user_data[:locked] || false
- attachment = get_in(new_user_data, [:source_data, "attachment"]) || []
- invisible = new_user_data[:invisible] || false
-
- fields =
- attachment
- |> Enum.filter(fn %{"type" => t} -> t == "PropertyValue" end)
- |> Enum.map(fn fields -> Map.take(fields, ["name", "value"]) end)
-
- update_data =
- new_user_data
- |> Map.take([:avatar, :banner, :bio, :name, :also_known_as])
- |> Map.put(:fields, fields)
- |> Map.put(:locked, locked)
- |> Map.put(:invisible, invisible)
-
actor
- |> User.upgrade_changeset(update_data, true)
+ |> User.upgrade_changeset(new_user_data, true)
|> User.update_and_set_cache()
ActivityPub.update(%{
diff --git a/lib/pleroma/web/activity_pub/utils.ex b/lib/pleroma/web/activity_pub/utils.ex
index db7084246..4f7fdaf38 100644
--- a/lib/pleroma/web/activity_pub/utils.ex
+++ b/lib/pleroma/web/activity_pub/utils.ex
@@ -312,19 +312,12 @@ defmodule Pleroma.Web.ActivityPub.Utils do
|> Map.put("content", emoji)
end
- @spec update_element_in_object(String.t(), list(any), Object.t()) ::
+ @spec update_element_in_object(String.t(), list(any), Object.t(), integer() | nil) ::
{:ok, Object.t()} | {:error, Ecto.Changeset.t()}
- def update_element_in_object(property, element, object) do
+ def update_element_in_object(property, element, object, count \\ nil) do
length =
- if is_map(element) do
- element
- |> Map.values()
- |> List.flatten()
- |> length()
- else
- element
- |> length()
- end
+ count ||
+ length(element)
data =
Map.merge(
@@ -344,29 +337,60 @@ defmodule Pleroma.Web.ActivityPub.Utils do
%Activity{data: %{"content" => emoji, "actor" => actor}},
object
) do
- reactions = object.data["reactions"] || %{}
- emoji_actors = reactions[emoji] || []
- new_emoji_actors = [actor | emoji_actors] |> Enum.uniq()
- new_reactions = Map.put(reactions, emoji, new_emoji_actors)
- update_element_in_object("reaction", new_reactions, object)
+ reactions = get_cached_emoji_reactions(object)
+
+ new_reactions =
+ case Enum.find_index(reactions, fn [candidate, _] -> emoji == candidate end) do
+ nil ->
+ reactions ++ [[emoji, [actor]]]
+
+ index ->
+ List.update_at(
+ reactions,
+ index,
+ fn [emoji, users] -> [emoji, Enum.uniq([actor | users])] end
+ )
+ end
+
+ count = emoji_count(new_reactions)
+
+ update_element_in_object("reaction", new_reactions, object, count)
+ end
+
+ def emoji_count(reactions_list) do
+ Enum.reduce(reactions_list, 0, fn [_, users], acc -> acc + length(users) end)
end
def remove_emoji_reaction_from_object(
%Activity{data: %{"content" => emoji, "actor" => actor}},
object
) do
- reactions = object.data["reactions"] || %{}
- emoji_actors = reactions[emoji] || []
- new_emoji_actors = List.delete(emoji_actors, actor)
+ reactions = get_cached_emoji_reactions(object)
new_reactions =
- if new_emoji_actors == [] do
- Map.delete(reactions, emoji)
- else
- Map.put(reactions, emoji, new_emoji_actors)
+ case Enum.find_index(reactions, fn [candidate, _] -> emoji == candidate end) do
+ nil ->
+ reactions
+
+ index ->
+ List.update_at(
+ reactions,
+ index,
+ fn [emoji, users] -> [emoji, List.delete(users, actor)] end
+ )
+ |> Enum.reject(fn [_, users] -> Enum.empty?(users) end)
end
- update_element_in_object("reaction", new_reactions, object)
+ count = emoji_count(new_reactions)
+ update_element_in_object("reaction", new_reactions, object, count)
+ end
+
+ def get_cached_emoji_reactions(object) do
+ if is_list(object.data["reactions"]) do
+ object.data["reactions"]
+ else
+ []
+ end
end
@spec add_like_to_object(Activity.t(), Object.t()) ::
diff --git a/lib/pleroma/web/admin_api/admin_api_controller.ex b/lib/pleroma/web/admin_api/admin_api_controller.ex
index 529169c1b..2314d3274 100644
--- a/lib/pleroma/web/admin_api/admin_api_controller.ex
+++ b/lib/pleroma/web/admin_api/admin_api_controller.ex
@@ -4,7 +4,11 @@
defmodule Pleroma.Web.AdminAPI.AdminAPIController do
use Pleroma.Web, :controller
+
+ import Pleroma.Web.ControllerHelper, only: [json_response: 3]
+
alias Pleroma.Activity
+ alias Pleroma.ConfigDB
alias Pleroma.ModerationLog
alias Pleroma.Plugs.OAuthScopesPlug
alias Pleroma.ReportNote
@@ -14,7 +18,6 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIController do
alias Pleroma.Web.ActivityPub.Relay
alias Pleroma.Web.ActivityPub.Utils
alias Pleroma.Web.AdminAPI.AccountView
- alias Pleroma.Web.AdminAPI.Config
alias Pleroma.Web.AdminAPI.ConfigView
alias Pleroma.Web.AdminAPI.ModerationLogView
alias Pleroma.Web.AdminAPI.Report
@@ -25,10 +28,11 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIController do
alias Pleroma.Web.MastodonAPI.StatusView
alias Pleroma.Web.Router
- import Pleroma.Web.ControllerHelper, only: [json_response: 3]
-
require Logger
+ @descriptions_json Pleroma.Docs.JSON.compile()
+ @users_page_size 50
+
plug(
OAuthScopesPlug,
%{scopes: ["read:accounts"], admin: true}
@@ -75,7 +79,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIController do
plug(
OAuthScopesPlug,
%{scopes: ["write:reports"], admin: true}
- when action in [:report_update_state, :report_respond]
+ when action in [:reports_update]
)
plug(
@@ -93,7 +97,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIController do
plug(
OAuthScopesPlug,
%{scopes: ["read"], admin: true}
- when action in [:config_show, :migrate_to_db, :migrate_from_db, :list_log]
+ when action in [:config_show, :migrate_from_db, :list_log]
)
plug(
@@ -102,8 +106,6 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIController do
when action == :config_update
)
- @users_page_size 50
-
action_fallback(:errors)
def user_delete(%{assigns: %{user: admin}} = conn, %{"nickname" => nickname}) do
@@ -639,7 +641,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIController do
def force_password_reset(%{assigns: %{user: admin}} = conn, %{"nicknames" => nicknames}) do
users = nicknames |> Enum.map(&User.get_cached_by_nickname/1)
- Enum.map(users, &User.force_password_reset_async/1)
+ Enum.each(users, &User.force_password_reset_async/1)
ModerationLog.insert_log(%{
actor: admin,
@@ -785,49 +787,132 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIController do
|> render("index.json", %{log: log})
end
- def migrate_to_db(conn, _params) do
- Mix.Tasks.Pleroma.Config.run(["migrate_to_db"])
- json(conn, %{})
+ def config_descriptions(conn, _params) do
+ conn
+ |> Plug.Conn.put_resp_content_type("application/json")
+ |> Plug.Conn.send_resp(200, @descriptions_json)
end
def migrate_from_db(conn, _params) do
- Mix.Tasks.Pleroma.Config.run(["migrate_from_db", Pleroma.Config.get(:env), "true"])
- json(conn, %{})
+ with :ok <- configurable_from_database(conn) do
+ Mix.Tasks.Pleroma.Config.run([
+ "migrate_from_db",
+ "--env",
+ to_string(Pleroma.Config.get(:env)),
+ "-d"
+ ])
+
+ json(conn, %{})
+ end
end
- def config_show(conn, _params) do
- configs = Pleroma.Repo.all(Config)
+ def config_show(conn, %{"only_db" => true}) do
+ with :ok <- configurable_from_database(conn) do
+ configs = Pleroma.Repo.all(ConfigDB)
- conn
- |> put_view(ConfigView)
- |> render("index.json", %{configs: configs})
+ if configs == [] do
+ errors(
+ conn,
+ {:error, "To use configuration from database migrate your settings to database."}
+ )
+ else
+ conn
+ |> put_view(ConfigView)
+ |> render("index.json", %{configs: configs})
+ end
+ end
end
- def config_update(conn, %{"configs" => configs}) do
- updated =
- if Pleroma.Config.get([:instance, :dynamic_configuration]) do
- updated =
- Enum.map(configs, fn
- %{"group" => group, "key" => key, "delete" => "true"} = params ->
- {:ok, config} = Config.delete(%{group: group, key: key, subkeys: params["subkeys"]})
- config
-
- %{"group" => group, "key" => key, "value" => value} ->
- {:ok, config} = Config.update_or_create(%{group: group, key: key, value: value})
- config
+ def config_show(conn, _params) do
+ with :ok <- configurable_from_database(conn) do
+ configs = ConfigDB.get_all_as_keyword()
+
+ if configs == [] do
+ errors(
+ conn,
+ {:error, "To use configuration from database migrate your settings to database."}
+ )
+ else
+ merged =
+ Pleroma.Config.Holder.config()
+ |> ConfigDB.merge(configs)
+ |> Enum.map(fn {group, values} ->
+ Enum.map(values, fn {key, value} ->
+ db =
+ if configs[group][key] do
+ ConfigDB.get_db_keys(configs[group][key], key)
+ end
+
+ db_value = configs[group][key]
+
+ merged_value =
+ if !is_nil(db_value) and Keyword.keyword?(db_value) and
+ ConfigDB.sub_key_full_update?(group, key, Keyword.keys(db_value)) do
+ ConfigDB.merge_group(group, key, value, db_value)
+ else
+ value
+ end
+
+ setting = %{
+ group: ConfigDB.convert(group),
+ key: ConfigDB.convert(key),
+ value: ConfigDB.convert(merged_value)
+ }
+
+ if db, do: Map.put(setting, :db, db), else: setting
+ end)
end)
- |> Enum.reject(&is_nil(&1))
+ |> List.flatten()
- Pleroma.Config.TransferTask.load_and_update_env()
- Mix.Tasks.Pleroma.Config.run(["migrate_from_db", Pleroma.Config.get(:env), "false"])
- updated
- else
- []
+ json(conn, %{configs: merged})
end
+ end
+ end
- conn
- |> put_view(ConfigView)
- |> render("index.json", %{configs: updated})
+ def config_update(conn, %{"configs" => configs}) do
+ with :ok <- configurable_from_database(conn) do
+ {_errors, results} =
+ Enum.map(configs, fn
+ %{"group" => group, "key" => key, "delete" => true} = params ->
+ ConfigDB.delete(%{group: group, key: key, subkeys: params["subkeys"]})
+
+ %{"group" => group, "key" => key, "value" => value} ->
+ ConfigDB.update_or_create(%{group: group, key: key, value: value})
+ end)
+ |> Enum.split_with(fn result -> elem(result, 0) == :error end)
+
+ {deleted, updated} =
+ results
+ |> Enum.map(fn {:ok, config} ->
+ Map.put(config, :db, ConfigDB.get_db_keys(config))
+ end)
+ |> Enum.split_with(fn config ->
+ Ecto.get_meta(config, :state) == :deleted
+ end)
+
+ Pleroma.Config.TransferTask.load_and_update_env(deleted)
+
+ Mix.Tasks.Pleroma.Config.run([
+ "migrate_from_db",
+ "--env",
+ to_string(Pleroma.Config.get(:env))
+ ])
+
+ conn
+ |> put_view(ConfigView)
+ |> render("index.json", %{configs: updated})
+ end
+ end
+
+ defp configurable_from_database(conn) do
+ if Pleroma.Config.get(:configurable_from_database) do
+ :ok
+ else
+ errors(
+ conn,
+ {:error, "To use this endpoint you need to enable configuration from database."}
+ )
+ end
end
def reload_emoji(conn, _params) do
diff --git a/lib/pleroma/web/admin_api/config.ex b/lib/pleroma/web/admin_api/config.ex
deleted file mode 100644
index 1917a5580..000000000
--- a/lib/pleroma/web/admin_api/config.ex
+++ /dev/null
@@ -1,182 +0,0 @@
-# Pleroma: A lightweight social networking server
-# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
-# SPDX-License-Identifier: AGPL-3.0-only
-
-defmodule Pleroma.Web.AdminAPI.Config do
- use Ecto.Schema
- import Ecto.Changeset
- import Pleroma.Web.Gettext
- alias __MODULE__
- alias Pleroma.Repo
-
- @type t :: %__MODULE__{}
-
- schema "config" do
- field(:key, :string)
- field(:group, :string)
- field(:value, :binary)
-
- timestamps()
- end
-
- @spec get_by_params(map()) :: Config.t() | nil
- def get_by_params(params), do: Repo.get_by(Config, params)
-
- @spec changeset(Config.t(), map()) :: Changeset.t()
- def changeset(config, params \\ %{}) do
- config
- |> cast(params, [:key, :group, :value])
- |> validate_required([:key, :group, :value])
- |> unique_constraint(:key, name: :config_group_key_index)
- end
-
- @spec create(map()) :: {:ok, Config.t()} | {:error, Changeset.t()}
- def create(params) do
- %Config{}
- |> changeset(Map.put(params, :value, transform(params[:value])))
- |> Repo.insert()
- end
-
- @spec update(Config.t(), map()) :: {:ok, Config} | {:error, Changeset.t()}
- def update(%Config{} = config, %{value: value}) do
- config
- |> change(value: transform(value))
- |> Repo.update()
- end
-
- @spec update_or_create(map()) :: {:ok, Config.t()} | {:error, Changeset.t()}
- def update_or_create(params) do
- with %Config{} = config <- Config.get_by_params(Map.take(params, [:group, :key])) do
- Config.update(config, params)
- else
- nil -> Config.create(params)
- end
- end
-
- @spec delete(map()) :: {:ok, Config.t()} | {:error, Changeset.t()}
- def delete(params) do
- with %Config{} = config <- Config.get_by_params(Map.delete(params, :subkeys)) do
- if params[:subkeys] do
- updated_value =
- Keyword.drop(
- :erlang.binary_to_term(config.value),
- Enum.map(params[:subkeys], &do_transform_string(&1))
- )
-
- Config.update(config, %{value: updated_value})
- else
- Repo.delete(config)
- {:ok, nil}
- end
- else
- nil ->
- err =
- dgettext("errors", "Config with params %{params} not found", params: inspect(params))
-
- {:error, err}
- end
- end
-
- @spec from_binary(binary()) :: term()
- def from_binary(binary), do: :erlang.binary_to_term(binary)
-
- @spec from_binary_with_convert(binary()) :: any()
- def from_binary_with_convert(binary) do
- from_binary(binary)
- |> do_convert()
- end
-
- defp do_convert(entity) when is_list(entity) do
- for v <- entity, into: [], do: do_convert(v)
- end
-
- defp do_convert(%Regex{} = entity), do: inspect(entity)
-
- defp do_convert(entity) when is_map(entity) do
- for {k, v} <- entity, into: %{}, do: {do_convert(k), do_convert(v)}
- end
-
- defp do_convert({:dispatch, [entity]}), do: %{"tuple" => [":dispatch", [inspect(entity)]]}
- defp do_convert({:partial_chain, entity}), do: %{"tuple" => [":partial_chain", inspect(entity)]}
-
- defp do_convert(entity) when is_tuple(entity),
- do: %{"tuple" => do_convert(Tuple.to_list(entity))}
-
- defp do_convert(entity) when is_boolean(entity) or is_number(entity) or is_nil(entity),
- do: entity
-
- defp do_convert(entity) when is_atom(entity) do
- string = to_string(entity)
-
- if String.starts_with?(string, "Elixir."),
- do: do_convert(string),
- else: ":" <> string
- end
-
- defp do_convert("Elixir." <> module_name), do: module_name
-
- defp do_convert(entity) when is_binary(entity), do: entity
-
- @spec transform(any()) :: binary()
- def transform(entity) when is_binary(entity) or is_map(entity) or is_list(entity) do
- :erlang.term_to_binary(do_transform(entity))
- end
-
- def transform(entity), do: :erlang.term_to_binary(entity)
-
- defp do_transform(%Regex{} = entity), do: entity
-
- defp do_transform(%{"tuple" => [":dispatch", [entity]]}) do
- {dispatch_settings, []} = do_eval(entity)
- {:dispatch, [dispatch_settings]}
- end
-
- defp do_transform(%{"tuple" => [":partial_chain", entity]}) do
- {partial_chain, []} = do_eval(entity)
- {:partial_chain, partial_chain}
- end
-
- defp do_transform(%{"tuple" => entity}) do
- Enum.reduce(entity, {}, fn val, acc -> Tuple.append(acc, do_transform(val)) end)
- end
-
- defp do_transform(entity) when is_map(entity) do
- for {k, v} <- entity, into: %{}, do: {do_transform(k), do_transform(v)}
- end
-
- defp do_transform(entity) when is_list(entity) do
- for v <- entity, into: [], do: do_transform(v)
- end
-
- defp do_transform(entity) when is_binary(entity) do
- String.trim(entity)
- |> do_transform_string()
- end
-
- defp do_transform(entity), do: entity
-
- defp do_transform_string("~r/" <> pattern) do
- modificator = String.split(pattern, "/") |> List.last()
- pattern = String.trim_trailing(pattern, "/" <> modificator)
-
- case modificator do
- "" -> ~r/#{pattern}/
- "i" -> ~r/#{pattern}/i
- "u" -> ~r/#{pattern}/u
- "s" -> ~r/#{pattern}/s
- end
- end
-
- defp do_transform_string(":" <> atom), do: String.to_atom(atom)
-
- defp do_transform_string(value) do
- if String.starts_with?(value, "Pleroma") or String.starts_with?(value, "Phoenix"),
- do: String.to_existing_atom("Elixir." <> value),
- else: value
- end
-
- defp do_eval(entity) do
- cleaned_string = String.replace(entity, ~r/[^\w|^{:,[|^,|^[|^\]^}|^\/|^\.|^"]^\s/, "")
- Code.eval_string(cleaned_string, [], requires: [], macros: [])
- end
-end
diff --git a/lib/pleroma/web/admin_api/views/config_view.ex b/lib/pleroma/web/admin_api/views/config_view.ex
index 49add0b6e..23d97e847 100644
--- a/lib/pleroma/web/admin_api/views/config_view.ex
+++ b/lib/pleroma/web/admin_api/views/config_view.ex
@@ -12,10 +12,16 @@ defmodule Pleroma.Web.AdminAPI.ConfigView do
end
def render("show.json", %{config: config}) do
- %{
+ map = %{
key: config.key,
group: config.group,
- value: Pleroma.Web.AdminAPI.Config.from_binary_with_convert(config.value)
+ value: Pleroma.ConfigDB.from_binary_with_convert(config.value)
}
+
+ if config.db != [] do
+ Map.put(map, :db, config.db)
+ else
+ map
+ end
end
end
diff --git a/lib/pleroma/web/common_api/common_api.ex b/lib/pleroma/web/common_api/common_api.ex
index 2f3bcfc3c..c05a6c544 100644
--- a/lib/pleroma/web/common_api/common_api.ex
+++ b/lib/pleroma/web/common_api/common_api.ex
@@ -85,9 +85,13 @@ defmodule Pleroma.Web.CommonAPI do
def repeat(id_or_ap_id, user, params \\ %{}) do
with %Activity{} = activity <- get_by_id_or_ap_id(id_or_ap_id),
object <- Object.normalize(activity),
- nil <- Utils.get_existing_announce(user.ap_id, object),
+ announce_activity <- Utils.get_existing_announce(user.ap_id, object),
public <- public_announce?(object, params) do
- ActivityPub.announce(user, object, nil, true, public)
+ if announce_activity do
+ {:ok, announce_activity, object}
+ else
+ ActivityPub.announce(user, object, nil, true, public)
+ end
else
_ -> {:error, dgettext("errors", "Could not repeat")}
end
@@ -105,8 +109,12 @@ 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),
- nil <- Utils.get_existing_like(user.ap_id, object) do
- ActivityPub.like(user, object)
+ like_activity <- Utils.get_existing_like(user.ap_id, object) do
+ if like_activity do
+ {:ok, like_activity, object}
+ else
+ ActivityPub.like(user, object)
+ end
else
_ -> {:error, dgettext("errors", "Could not favorite")}
end
diff --git a/lib/pleroma/web/mastodon_api/controllers/search_controller.ex b/lib/pleroma/web/mastodon_api/controllers/search_controller.ex
index 0a929f55b..5a5db8e00 100644
--- a/lib/pleroma/web/mastodon_api/controllers/search_controller.ex
+++ b/lib/pleroma/web/mastodon_api/controllers/search_controller.ex
@@ -43,7 +43,7 @@ defmodule Pleroma.Web.MastodonAPI.SearchController do
result =
default_values
|> Enum.map(fn {resource, default_value} ->
- if params["type"] == nil or params["type"] == resource do
+ if params["type"] in [nil, resource] do
{resource, fn -> resource_search(version, resource, query, options) end}
else
{resource, fn -> default_value end}
diff --git a/lib/pleroma/web/mastodon_api/controllers/subscription_controller.ex b/lib/pleroma/web/mastodon_api/controllers/subscription_controller.ex
index fc7d52824..11f7b85d3 100644
--- a/lib/pleroma/web/mastodon_api/controllers/subscription_controller.ex
+++ b/lib/pleroma/web/mastodon_api/controllers/subscription_controller.ex
@@ -6,9 +6,9 @@ defmodule Pleroma.Web.MastodonAPI.SubscriptionController do
@moduledoc "The module represents functions to manage user subscriptions."
use Pleroma.Web, :controller
+ alias Pleroma.Web.MastodonAPI.PushSubscriptionView, as: View
alias Pleroma.Web.Push
alias Pleroma.Web.Push.Subscription
- alias Pleroma.Web.MastodonAPI.PushSubscriptionView, as: View
action_fallback(:errors)
diff --git a/lib/pleroma/web/mastodon_api/controllers/timeline_controller.ex b/lib/pleroma/web/mastodon_api/controllers/timeline_controller.ex
index 384159336..29964a1d4 100644
--- a/lib/pleroma/web/mastodon_api/controllers/timeline_controller.ex
+++ b/lib/pleroma/web/mastodon_api/controllers/timeline_controller.ex
@@ -77,10 +77,7 @@ defmodule Pleroma.Web.MastodonAPI.TimelineController do
|> render("index.json", activities: activities, for: user, as: :activity)
end
- # GET /api/v1/timelines/tag/:tag
- def hashtag(%{assigns: %{user: user}} = conn, params) do
- local_only = truthy_param?(params["local"])
-
+ def hashtag_fetching(params, user, local_only) do
tags =
[params["tag"], params["any"]]
|> List.flatten()
@@ -98,7 +95,7 @@ defmodule Pleroma.Web.MastodonAPI.TimelineController do
|> Map.get("none", [])
|> Enum.map(&String.downcase(&1))
- activities =
+ _activities =
params
|> Map.put("type", "Create")
|> Map.put("local_only", local_only)
@@ -109,6 +106,13 @@ defmodule Pleroma.Web.MastodonAPI.TimelineController do
|> Map.put("tag_all", tag_all)
|> Map.put("tag_reject", tag_reject)
|> ActivityPub.fetch_public_activities()
+ end
+
+ # GET /api/v1/timelines/tag/:tag
+ def hashtag(%{assigns: %{user: user}} = conn, params) do
+ local_only = truthy_param?(params["local"])
+
+ activities = hashtag_fetching(params, user, local_only)
conn
|> add_link_headers(activities, %{"local" => local_only})
diff --git a/lib/pleroma/web/mastodon_api/views/notification_view.ex b/lib/pleroma/web/mastodon_api/views/notification_view.ex
index ddd7f5318..360ec10f0 100644
--- a/lib/pleroma/web/mastodon_api/views/notification_view.ex
+++ b/lib/pleroma/web/mastodon_api/views/notification_view.ex
@@ -37,18 +37,37 @@ defmodule Pleroma.Web.MastodonAPI.NotificationView do
}
case mastodon_type do
- "mention" -> put_status(response, activity, user)
- "favourite" -> put_status(response, parent_activity, user)
- "reblog" -> put_status(response, parent_activity, user)
- "move" -> put_target(response, activity, user)
- "follow" -> response
- _ -> nil
+ "mention" ->
+ put_status(response, activity, user)
+
+ "favourite" ->
+ put_status(response, parent_activity, user)
+
+ "reblog" ->
+ put_status(response, parent_activity, user)
+
+ "move" ->
+ put_target(response, activity, user)
+
+ "follow" ->
+ response
+
+ "pleroma:emoji_reaction" ->
+ put_status(response, parent_activity, user) |> put_emoji(activity)
+
+ _ ->
+ nil
end
else
_ -> nil
end
end
+ defp put_emoji(response, activity) do
+ response
+ |> Map.put(:emoji, activity.data["content"])
+ end
+
defp put_status(response, activity, user) do
Map.put(response, :status, StatusView.render("show.json", %{activity: activity, for: user}))
end
diff --git a/lib/pleroma/web/mastodon_api/views/status_view.ex b/lib/pleroma/web/mastodon_api/views/status_view.ex
index e9590224b..e60ef709b 100644
--- a/lib/pleroma/web/mastodon_api/views/status_view.ex
+++ b/lib/pleroma/web/mastodon_api/views/status_view.ex
@@ -253,6 +253,15 @@ defmodule Pleroma.Web.MastodonAPI.StatusView do
nil
end
+ emoji_reactions =
+ with %{data: %{"reactions" => emoji_reactions}} <- object do
+ Enum.map(emoji_reactions, fn [emoji, users] ->
+ %{emoji: emoji, count: length(users)}
+ end)
+ else
+ _ -> []
+ end
+
%{
id: to_string(activity.id),
uri: object.data["id"],
@@ -293,7 +302,8 @@ defmodule Pleroma.Web.MastodonAPI.StatusView do
spoiler_text: %{"text/plain" => summary_plaintext},
expires_at: expires_at,
direct_conversation_id: direct_conversation_id,
- thread_muted: thread_muted?
+ thread_muted: thread_muted?,
+ emoji_reactions: emoji_reactions
}
}
end
diff --git a/lib/pleroma/web/oauth/oauth_controller.ex b/lib/pleroma/web/oauth/oauth_controller.ex
index d5c0d97c0..528f08574 100644
--- a/lib/pleroma/web/oauth/oauth_controller.ex
+++ b/lib/pleroma/web/oauth/oauth_controller.ex
@@ -14,10 +14,10 @@ defmodule Pleroma.Web.OAuth.OAuthController do
alias Pleroma.Web.ControllerHelper
alias Pleroma.Web.OAuth.App
alias Pleroma.Web.OAuth.Authorization
+ alias Pleroma.Web.OAuth.Scopes
alias Pleroma.Web.OAuth.Token
alias Pleroma.Web.OAuth.Token.Strategy.RefreshToken
alias Pleroma.Web.OAuth.Token.Strategy.Revoke, as: RevokeToken
- alias Pleroma.Web.OAuth.Scopes
require Logger
diff --git a/lib/pleroma/web/pleroma_api/controllers/pleroma_api_controller.ex b/lib/pleroma/web/pleroma_api/controllers/pleroma_api_controller.ex
index 772c535a4..cd1c0764f 100644
--- a/lib/pleroma/web/pleroma_api/controllers/pleroma_api_controller.ex
+++ b/lib/pleroma/web/pleroma_api/controllers/pleroma_api_controller.ex
@@ -23,7 +23,7 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIController do
plug(
OAuthScopesPlug,
%{scopes: ["read:statuses"]}
- when action in [:conversation, :conversation_statuses, :emoji_reactions_by]
+ when action in [:conversation, :conversation_statuses]
)
plug(
@@ -43,21 +43,26 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIController do
def emoji_reactions_by(%{assigns: %{user: user}} = conn, %{"id" => activity_id}) do
with %Activity{} = activity <- Activity.get_by_id_with_object(activity_id),
- %Object{data: %{"reactions" => emoji_reactions}} <- Object.normalize(activity) do
+ %Object{data: %{"reactions" => emoji_reactions}} when is_list(emoji_reactions) <-
+ Object.normalize(activity) do
reactions =
emoji_reactions
- |> Enum.map(fn {emoji, users} ->
+ |> Enum.map(fn [emoji, users] ->
users = Enum.map(users, &User.get_cached_by_ap_id/1)
- {emoji, AccountView.render("index.json", %{users: users, for: user, as: :user})}
+
+ %{
+ emoji: emoji,
+ count: length(users),
+ accounts: AccountView.render("index.json", %{users: users, for: user, as: :user})
+ }
end)
- |> Enum.into(%{})
conn
|> json(reactions)
else
_e ->
conn
- |> json(%{})
+ |> json([])
end
end
diff --git a/lib/pleroma/web/router.ex b/lib/pleroma/web/router.ex
index 9654ab8a3..ef6e5a565 100644
--- a/lib/pleroma/web/router.ex
+++ b/lib/pleroma/web/router.ex
@@ -195,7 +195,7 @@ defmodule Pleroma.Web.Router do
get("/config", AdminAPIController, :config_show)
post("/config", AdminAPIController, :config_update)
- get("/config/migrate_to_db", AdminAPIController, :migrate_to_db)
+ get("/config/descriptions", AdminAPIController, :config_descriptions)
get("/config/migrate_from_db", AdminAPIController, :migrate_from_db)
get("/moderation_log", AdminAPIController, :list_log)
diff --git a/lib/pleroma/workers/attachments_cleanup_worker.ex b/lib/pleroma/workers/attachments_cleanup_worker.ex
new file mode 100644
index 000000000..3f421db40
--- /dev/null
+++ b/lib/pleroma/workers/attachments_cleanup_worker.ex
@@ -0,0 +1,88 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.Workers.AttachmentsCleanupWorker do
+ import Ecto.Query
+
+ alias Pleroma.Object
+ alias Pleroma.Repo
+
+ use Pleroma.Workers.WorkerHelper, queue: "attachments_cleanup"
+
+ @impl Oban.Worker
+ def perform(
+ %{"object" => %{"data" => %{"attachment" => [_ | _] = attachments, "actor" => actor}}},
+ _job
+ ) do
+ hrefs =
+ Enum.flat_map(attachments, fn attachment ->
+ Enum.map(attachment["url"], & &1["href"])
+ end)
+
+ names = Enum.map(attachments, & &1["name"])
+
+ uploader = Pleroma.Config.get([Pleroma.Upload, :uploader])
+
+ # find all objects for copies of the attachments, name and actor doesn't matter here
+ delete_ids =
+ from(o in Object,
+ where:
+ fragment(
+ "to_jsonb(array(select jsonb_array_elements((?)#>'{url}') ->> 'href' where jsonb_typeof((?)#>'{url}') = 'array'))::jsonb \\?| (?)",
+ o.data,
+ o.data,
+ ^hrefs
+ )
+ )
+ # The query above can be time consumptive on large instances until we
+ # refactor how uploads are stored
+ |> Repo.all(timout: :infinity)
+ # we should delete 1 object for any given attachment, but don't delete
+ # files if there are more than 1 object for it
+ |> Enum.reduce(%{}, fn %{
+ id: id,
+ data: %{
+ "url" => [%{"href" => href}],
+ "actor" => obj_actor,
+ "name" => name
+ }
+ },
+ acc ->
+ Map.update(acc, href, %{id: id, count: 1}, fn val ->
+ case obj_actor == actor and name in names do
+ true ->
+ # set id of the actor's object that will be deleted
+ %{val | id: id, count: val.count + 1}
+
+ false ->
+ # another actor's object, just increase count to not delete file
+ %{val | count: val.count + 1}
+ end
+ end)
+ end)
+ |> Enum.map(fn {href, %{id: id, count: count}} ->
+ # only delete files that have single instance
+ with 1 <- count do
+ prefix =
+ case Pleroma.Config.get([Pleroma.Upload, :base_url]) do
+ nil -> "media"
+ _ -> ""
+ end
+
+ base_url = Pleroma.Config.get([__MODULE__, :base_url], Pleroma.Web.base_url())
+
+ file_path = String.trim_leading(href, "#{base_url}/#{prefix}")
+
+ uploader.delete_file(file_path)
+ end
+
+ id
+ end)
+
+ from(o in Object, where: o.id in ^delete_ids)
+ |> Repo.delete_all()
+ end
+
+ def perform(%{"object" => _object}, _job), do: :ok
+end