diff options
18 files changed, 813 insertions, 82 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md index 755b28d5b..0a8163135 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,11 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ### Added - Refreshing poll results for remote polls - Admin API: Add ability to require password reset +- Pleroma API: `GET /api/v1/pleroma/subscription_notifications/` to get list of subscription notifications +- Pleroma API: `GET /api/v1/pleroma/subscription_notifications/:id` to get a subscription notification +- Pleroma API: `POST /api/v1/pleroma/subscription_notifications/clear` to clear all subscription notifications +- Pleroma API: `POST /api/v1/pleroma/subscription_notifications/dismiss` to clear a subscription notification +- Pleroma API: `DELETE /api/v1/pleroma/subscription_notifications/destroy_multiple` to clear multiple subscription notifications ### Changed - **Breaking:** Elixir >=1.8 is now required (was >= 1.7) @@ -15,6 +20,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). - Admin API: Return `total` when querying for reports - Mastodon API: Return `pleroma.direct_conversation_id` when creating a direct message (`POST /api/v1/statuses`) - Admin API: Return link alongside with token on password reset +- Mastodon API: notifications no longer include subscription notifications - they are now served from new endpoints in Pleroma API ### Fixed - Mastodon API: Fix private and direct statuses not being filtered out from the public timeline for an authenticated user (`GET /api/v1/timelines/public`) diff --git a/docs/api/admin_api.md b/docs/api/admin_api.md index 573111416..fcdb33944 100644 --- a/docs/api/admin_api.md +++ b/docs/api/admin_api.md @@ -711,6 +711,7 @@ Compile time settings (need instance reboot): } ] } +``` - Response: diff --git a/docs/api/pleroma_api.md b/docs/api/pleroma_api.md index a469ddfbf..ac5489aa3 100644 --- a/docs/api/pleroma_api.md +++ b/docs/api/pleroma_api.md @@ -423,6 +423,15 @@ The status posting endpoint takes an additional parameter, `in_reply_to_conversa * Response: JSON, "ok" and 200 status if the pack was downloaded, or 500 if there were errors downloading the pack +## `POST /api/pleroma/emoji/packs/list_from` +### Requests the instance to list the packs from another instance +* Method `POST` +* Authentication: required +* Params: + * `instance_address`: the address of the instance to download from +* Response: JSON with the pack list, same as if the request was made to that instance's + list endpoint directly + 200 status + ## `GET /api/pleroma/emoji/packs/:name/download_shared` ### Requests a local pack from the instance * Method `GET` diff --git a/docs/installation/alpine_linux_en.md b/docs/installation/alpine_linux_en.md index 1f300f353..f200362ca 100644 --- a/docs/installation/alpine_linux_en.md +++ b/docs/installation/alpine_linux_en.md @@ -1,7 +1,9 @@ # Installing on Alpine Linux ## Installation -This guide is a step-by-step installation guide for Alpine Linux. It also assumes that you have administrative rights, either as root or a user with [sudo permissions](https://www.linode.com/docs/tools-reference/custom-kernels-distros/install-alpine-linux-on-your-linode/#configuration). If you want to run this guide with root, ignore the `sudo` at the beginning of the lines, unless it calls a user like `sudo -Hu pleroma`; in this case, use `su -l <username> -s $SHELL -c 'command'` instead. +This guide is a step-by-step installation guide for Alpine Linux. The instructions were verified against Alpine v3.10 standard image. You might miss additional dependencies if you use `netboot` instead. + +It assumes that you have administrative rights, either as root or a user with [sudo permissions](https://www.linode.com/docs/tools-reference/custom-kernels-distros/install-alpine-linux-on-your-linode/#configuration). If you want to run this guide with root, ignore the `sudo` at the beginning of the lines, unless it calls a user like `sudo -Hu pleroma`; in this case, use `su -l <username> -s $SHELL -c 'command'` instead. ### Required packages @@ -20,12 +22,13 @@ This guide is a step-by-step installation guide for Alpine Linux. It also assume ### Prepare the system -* First make sure to have the community repository enabled: +* The community repository must be enabled in `/etc/apk/repositories`. Depending on which version and mirror you use this looks like `http://alpine.42.fr/v3.10/community`. If you autogenerated the mirror during installation: ```shell -echo "https://nl.alpinelinux.org/alpine/latest-stable/community" | sudo tee -a /etc/apk/repository +awk 'NR==2' /etc/apk/repositories | sed 's/main/community/' | tee -a /etc/apk/repositories ``` + * Then update the system, if not already done: ```shell @@ -77,7 +80,8 @@ sudo rc-update add postgresql * Add a new system user for the Pleroma service: ```shell -sudo adduser -S -s /bin/false -h /opt/pleroma -H pleroma +sudo addgroup pleroma +sudo adduser -S -s /bin/false -h /opt/pleroma -H -G pleroma pleroma ``` **Note**: To execute a single command as the Pleroma system user, use `sudo -Hu pleroma command`. You can also switch to a shell by using `sudo -Hu pleroma $SHELL`. If you don’t have and want `sudo` on your system, you can use `su` as root user (UID 0) for a single command by using `su -l pleroma -s $SHELL -c 'command'` and `su -l pleroma -s $SHELL` for starting a shell. @@ -164,7 +168,26 @@ If that doesn’t work, make sure, that nginx is not already running. If it stil sudo cp /opt/pleroma/installation/pleroma.nginx /etc/nginx/conf.d/pleroma.conf ``` -* Before starting nginx edit the configuration and change it to your needs (e.g. change servername, change cert paths) +* Before starting nginx edit the configuration and change it to your needs. You must change change `server_name` and the paths to the certificates. You can use `nano` (install with `apk add nano` if missing). + +``` +server { + server_name your.domain; + listen 80; + ... +} + +server { + server_name your.domain; + listen 443 ssl http2; + ... + ssl_trusted_certificate /etc/letsencrypt/live/your.domain/chain.pem; + ssl_certificate /etc/letsencrypt/live/your.domain/fullchain.pem; + ssl_certificate_key /etc/letsencrypt/live/your.domain/privkey.pem; + ... +} +``` + * Enable and start nginx: ```shell diff --git a/docs/installation/debian_based_jp.md b/docs/installation/debian_based_jp.md index caf72363b..5ca6b3634 100644 --- a/docs/installation/debian_based_jp.md +++ b/docs/installation/debian_based_jp.md @@ -5,180 +5,179 @@ ## インストール -このガイドはDebian Stretchを仮定しています。Ubuntu 16.04でも可能です。 +このガイドはDebian Stretchを利用することを想定しています。Ubuntu 16.04や18.04でもおそらく動作します。また、ユーザはrootもしくはsudoにより管理者権限を持っていることを前提とします。もし、以下の操作をrootユーザで行う場合は、 `sudo` を無視してください。ただし、`sudo -Hu pleroma` のようにユーザを指定している場合には `su <username> -s $SHELL -c 'command'` を代わりに使ってください。 ### 必要なソフトウェア -- PostgreSQL 9.6+ (postgresql-contrib-9.6 または他のバージョンの PSQL をインストールしてください) -- Elixir 1.5 以上 ([Debianのリポジトリからインストールしないこと!!! ここからインストールすること!](https://elixir-lang.org/install.html#unix-and-unix-like))。または [asdf](https://github.com/asdf-vm/asdf) を pleroma ユーザーでインストール。 -- erlang-dev +- PostgreSQL 9.6以上 (Ubuntu16.04では9.5しか提供されていないので,[](https://www.postgresql.org/download/linux/ubuntu/)こちらから新しいバージョンを入手してください) +- postgresql-contrib 9.6以上 (同上) +- Elixir 1.5 以上 ([Debianのリポジトリからインストールしないこと!!! ここからインストールすること!](https://elixir-lang.org/install.html#unix-and-unix-like)。または [asdf](https://github.com/asdf-vm/asdf) をpleromaユーザーでインストールしてください) + - erlang-dev - erlang-tools - erlang-parsetools +- erlang-eldap (LDAP認証を有効化するときのみ必要) - erlang-ssh -- erlang-xmerl (Jessieではバックポートからインストールすること!) +- erlang-xmerl - git - build-essential -- openssh -- openssl -- nginx prefered (Apacheも動くかもしれませんが、誰もテストしていません!) -- certbot (または何らかのACME Let's encryptクライアント) + +#### このガイドで利用している追加パッケージ + +- nginx (おすすめです。他のリバースプロキシを使う場合は、参考となる設定をこのリポジトリから探してください) +- certbot (または何らかのLet's Encrypt向けACMEクライアント) ### システムを準備する * まずシステムをアップデートしてください。 ``` -apt update && apt dist-upgrade +sudo apt update +sudo apt full-upgrade ``` -* 複数のツールとpostgresqlをインストールします。あとで必要になるので。 +* 上記に挙げたパッケージをインストールしておきます。 ``` -apt install git build-essential openssl ssh sudo postgresql-9.6 postgresql-contrib-9.6 +sudo apt install git build-essential postgresql postgresql-contrib ``` -(postgresqlのバージョンは、あなたのディストロにあわせて変えてください。または、バージョン番号がいらないかもしれません。) + ### ElixirとErlangをインストールします * Erlangのリポジトリをダウンロードおよびインストールします。 ``` -wget -P /tmp/ https://packages.erlang-solutions.com/erlang-solutions_1.0_all.deb && sudo dpkg -i /tmp/erlang-solutions_1.0_all.deb +wget -P /tmp/ https://packages.erlang-solutions.com/erlang-solutions_1.0_all.deb +sudo dpkg -i /tmp/erlang-solutions_1.0_all.deb ``` * ElixirとErlangをインストールします、 ``` -apt update && apt install elixir erlang-dev erlang-parsetools erlang-xmerl erlang-tools erlang-ssh +sudo apt update +sudo apt install elixir erlang-dev erlang-parsetools erlang-xmerl erlang-tools erlang-ssh ``` ### Pleroma BE (バックエンド) をインストールします -* 新しいユーザーを作ります。 -``` -adduser pleroma -``` -(Give it any password you want, make it STRONG) +* Pleroma用に新しいユーザーを作ります。 -* 新しいユーザーをsudoグループに入れます。 ``` -usermod -aG sudo pleroma +sudo useradd -r -s /bin/false -m -d /var/lib/pleroma -U pleroma ``` -* 新しいユーザーに変身し、ホームディレクトリに移動します。 -``` -su pleroma -cd ~ -``` +**注意**: Pleromaユーザとして単発のコマンドを実行したい場合はは、`sudo -Hu pleroma command` を使ってください。シェルを使いたい場合は `sudo -Hu pleroma $SHELL`です。もし `sudo` を使わない場合は、rootユーザで `su -l pleroma -s $SHELL -c 'command'` とすることでコマンドを、`su -l pleroma -s $SHELL` とすることでシェルを開始できます。 * Gitリポジトリをクローンします。 ``` -git clone -b master https://git.pleroma.social/pleroma/pleroma +sudo mkdir -p /opt/pleroma +sudo chown -R pleroma:pleroma /opt/pleroma +sudo -Hu pleroma git clone -b master https://git.pleroma.social/pleroma/pleroma /opt/pleroma ``` * 新しいディレクトリに移動します。 ``` -cd pleroma/ +cd /opt/pleroma ``` * Pleromaが依存するパッケージをインストールします。Hexをインストールしてもよいか聞かれたら、yesを入力してください。 ``` -mix deps.get +sudo -Hu pleroma mix deps.get ``` * コンフィギュレーションを生成します。 ``` -mix pleroma.instance gen +sudo -Hu pleroma mix pleroma.instance gen ``` * rebar3をインストールしてもよいか聞かれたら、yesを入力してください。 - * この処理には時間がかかります。私もよく分かりませんが、何らかのコンパイルが行われているようです。 - * あなたのインスタンスについて、いくつかの質問があります。その回答は `config/generated_config.exs` というコンフィギュレーションファイルに保存されます。 + * このときにpleromaの一部がコンパイルされるため、この処理には時間がかかります。 + * あなたのインスタンスについて、いくつかの質問されます。この質問により `config/generated_config.exs` という設定ファイルが生成されます。 -**注意**: メディアプロクシを有効にすると回答して、なおかつ、キャッシュのURLは空欄のままにしている場合は、`generated_config.exs` を編集して、`base_url` で始まる行をコメントアウトまたは削除してください。そして、上にある行の `true` の後にあるコンマを消してください。 * コンフィギュレーションを確認して、もし問題なければ、ファイル名を変更してください。 ``` mv config/{generated_config.exs,prod.secret.exs} ``` -* これまでのコマンドで、すでに `config/setup_db.psql` というファイルが作られています。このファイルをもとに、データベースを作成します。 +* 先程のコマンドで、すでに `config/setup_db.psql` というファイルが作られています。このファイルをもとに、データベースを作成します。 ``` -sudo su postgres -c 'psql -f config/setup_db.psql' +sudo -Hu pleroma mix pleroma.instance gen ``` -* そして、データベースのミグレーションを実行します。 +* そして、データベースのマイグレーションを実行します。 ``` -MIX_ENV=prod mix ecto.migrate +sudo -Hu pleroma MIX_ENV=prod mix ecto.migrate ``` -* Pleromaを起動できるようになりました。 +* これでPleromaを起動できるようになりました。 ``` -MIX_ENV=prod mix phx.server +sudo -Hu pleroma MIX_ENV=prod mix phx.server ``` -### インストールを終わらせる +### インストールの最終段階 -あなたの新しいインスタンスを世界に向けて公開するには、nginxまたは何らかのウェブサーバー (プロクシ) を使用する必要があります。また、Pleroma のためにシステムサービスファイルを作成する必要があります。 +あなたの新しいインスタンスを世界に向けて公開するには、nginx等のWebサーバやプロキシサーバをPleromaの前段に使用する必要があります。また、Pleroma のためにシステムサービスファイルを作成する必要があります。 #### Nginx * まだインストールしていないなら、nginxをインストールします。 ``` -apt install nginx +sudo apt install nginx ``` * SSLをセットアップします。他の方法でもよいですが、ここではcertbotを説明します。 certbotを使うならば、まずそれをインストールします。 ``` -apt install certbot +sudo apt install certbot ``` そしてセットアップします。 ``` -mkdir -p /var/lib/letsencrypt/.well-known -% certbot certonly --email your@emailaddress --webroot -w /var/lib/letsencrypt/ -d yourdomain +sudo mkdir -p /var/lib/letsencrypt/ +sudo certbot certonly --email <your@emailaddress> -d <yourdomain> --standalone ``` -もしうまくいかないときは、先にnginxを設定してください。ssl "on" を "off" に変えてから再試行してください。 +もしうまくいかないときは、nginxが正しく動いていない可能性があります。先にnginxを設定してください。ssl "on" を "off" に変えてから再試行してください。 --- -* nginxコンフィギュレーションの例をnginxフォルダーにコピーします。 +* nginxの設定ファイルサンプルをnginxフォルダーにコピーします。 ``` -cp /home/pleroma/pleroma/installation/pleroma.nginx /etc/nginx/sites-enabled/pleroma.nginx +sudo cp /opt/pleroma/installation/pleroma.nginx /etc/nginx/sites-available/pleroma.nginx +sudo ln -s /etc/nginx/sites-available/pleroma.nginx /etc/nginx/sites-enabled/pleroma.nginx ``` -* nginxを起動する前に、コンフィギュレーションを編集してください。例えば、サーバー名、証明書のパスなどを変更する必要があります。 +* nginxを起動する前に、設定ファイルを編集してください。例えば、サーバー名、証明書のパスなどを変更する必要があります。 * nginxを再起動します。 ``` -systemctl reload nginx.service +sudo systemctl enable --now nginx.service ``` -#### Systemd サービス +もし証明書を更新する必要が出てきた場合には、nginxの関連するlocationブロックのコメントアウトを外し、以下のコマンドを動かします。 -* サービスファイルの例をコピーします。 ``` -cp /home/pleroma/pleroma/installation/pleroma.service /usr/lib/systemd/system/pleroma.service +sudo certbot certonly --email <your@emailaddress> -d <yourdomain> --webroot -w /var/lib/letsencrypt/ ``` -* サービスファイルを変更します。すべてのパスが正しいことを確認してください。また、`[Service]` セクションに以下の行があることを確認してください。 -``` -Environment="MIX_ENV=prod" -``` +#### 他のWebサーバやプロキシ +これに関してはサンプルが `/opt/pleroma/installation/` にあるので、探してみてください。 + +#### Systemd サービス -* `pleroma.service` を enable および start してください。 +* サービスファイルのサンプルをコピーします。 ``` -systemctl enable --now pleroma.service +sudo cp /opt/pleroma/installation/pleroma.service /etc/systemd/system/pleroma.service ``` -#### モデレーターを作る - -新たにユーザーを作ったら、モデレーター権限を与えたいかもしれません。以下のタスクで可能です。 +* サービスファイルを変更します。すべてのパスが正しいことを確認してください +* サービスを有効化し `pleroma.service` を開始してください ``` -mix set_moderator username [true|false] +sudo systemctl enable --now pleroma.service ``` -モデレーターはすべてのポストを消すことができます。将来的には他のことも可能になるかもしれません。 +#### 初期ユーザの作成 -#### メディアプロクシを有効にする +新たにインスタンスを作成したら、以下のコマンドにより管理者権限を持った初期ユーザを作成できます。 -`generate_config` でメディアプロクシを有効にしているなら、すでにメディアプロクシが動作しています。あとから設定を変更したいなら、[How to activate mediaproxy](How-to-activate-mediaproxy) を見てください。 +``` +sudo -Hu pleroma MIX_ENV=prod mix pleroma.user new <username> <your@emailaddress> --admin +``` -#### コンフィギュレーションとカスタマイズ +#### その他の設定とカスタマイズ * [Backup your instance](backup.html) * [Configuration tips](general-tips-for-customizing-pleroma-fe.html) diff --git a/lib/pleroma/notification.ex b/lib/pleroma/notification.ex index d94ae5971..d19924289 100644 --- a/lib/pleroma/notification.ex +++ b/lib/pleroma/notification.ex @@ -230,7 +230,6 @@ defmodule Pleroma.Notification do [] |> Utils.maybe_notify_to_recipients(activity) |> Utils.maybe_notify_mentioned_recipients(activity) - |> Utils.maybe_notify_subscribers(activity) |> Enum.uniq() User.get_users_from_set(recipients, local_only) diff --git a/lib/pleroma/subscription_notification.ex b/lib/pleroma/subscription_notification.ex new file mode 100644 index 000000000..1349d988c --- /dev/null +++ b/lib/pleroma/subscription_notification.ex @@ -0,0 +1,260 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.SubscriptionNotification do + use Ecto.Schema + + alias Pleroma.Activity + alias Pleroma.Object + alias Pleroma.Pagination + alias Pleroma.Repo + alias Pleroma.SubscriptionNotification + alias Pleroma.User + alias Pleroma.Web.CommonAPI.Utils + alias Pleroma.Web.Push + alias Pleroma.Web.Streamer + + import Ecto.Query + import Ecto.Changeset + + @type t :: %__MODULE__{} + + schema "subscription_notifications" do + belongs_to(:user, User, type: FlakeId.Ecto.CompatType) + belongs_to(:activity, Activity, type: FlakeId.Ecto.CompatType) + + timestamps() + end + + def changeset(%SubscriptionNotification{} = notification, attrs) do + cast(notification, attrs, []) + end + + def for_user_query(user, opts \\ []) do + query = + SubscriptionNotification + |> where(user_id: ^user.id) + |> where( + [n, a], + fragment( + "? not in (SELECT ap_id FROM users WHERE info->'deactivated' @> 'true')", + a.actor + ) + ) + |> join(:inner, [n], activity in assoc(n, :activity)) + |> join(:left, [n, a], object in Object, + on: + fragment( + "(?->>'id') = COALESCE((? -> 'object'::text) ->> 'id'::text)", + object.data, + a.data + ) + ) + |> preload([n, a, o], activity: {a, object: o}) + + if opts[:with_muted] do + query + else + query + |> where([n, a], a.actor not in ^user.info.muted_notifications) + |> where([n, a], a.actor not in ^user.info.blocks) + |> where( + [n, a], + fragment("substring(? from '.*://([^/]*)')", a.actor) not in ^user.info.domain_blocks + ) + |> join(:left, [n, a], tm in Pleroma.ThreadMute, + on: tm.user_id == ^user.id and tm.context == fragment("?->>'context'", a.data) + ) + |> where([n, a, o, tm], is_nil(tm.user_id)) + end + end + + def for_user(user, opts \\ %{}) do + user + |> for_user_query(opts) + |> Pagination.fetch_paginated(opts) + end + + @doc """ + Returns notifications for user received since given date. + + ## Examples + + iex> Pleroma.SubscriptionNotification.for_user_since(%Pleroma.User{}, ~N[2019-04-13 11:22:33]) + [%Pleroma.SubscriptionNotification{}, %Pleroma.SubscriptionNotification{}] + + iex> Pleroma.SubscriptionNotification.for_user_since(%Pleroma.User{}, ~N[2019-04-15 11:22:33]) + [] + """ + @spec for_user_since(Pleroma.User.t(), NaiveDateTime.t()) :: [t()] + def for_user_since(user, date) do + user + |> for_user_query() + |> where([n], n.updated_at > ^date) + |> Repo.all() + end + + def clear_up_to(%{id: user_id} = _user, id) do + from( + n in SubscriptionNotification, + where: n.user_id == ^user_id, + where: n.id <= ^id + ) + |> Repo.delete_all([]) + end + + def get(%{id: user_id} = _user, id) do + query = + from( + n in SubscriptionNotification, + where: n.id == ^id, + join: activity in assoc(n, :activity), + preload: [activity: activity] + ) + + case Repo.one(query) do + %{user_id: ^user_id} = notification -> + {:ok, notification} + + _ -> + {:error, "Cannot get notification"} + end + end + + def clear(user) do + from(n in SubscriptionNotification, where: n.user_id == ^user.id) + |> Repo.delete_all() + end + + def destroy_multiple(%{id: user_id} = _user, ids) do + from(n in SubscriptionNotification, + where: n.id in ^ids, + where: n.user_id == ^user_id + ) + |> Repo.delete_all() + end + + def dismiss(%{id: user_id} = _user, id) do + case Repo.get(SubscriptionNotification, id) do + %{user_id: ^user_id} = notification -> + Repo.delete(notification) + + _ -> + {:error, "Cannot dismiss notification"} + end + end + + def create_notifications(%Activity{data: %{"to" => _, "type" => "Create"}} = activity) do + case Object.normalize(activity) do + %{data: %{"type" => "Answer"}} -> + {:ok, []} + + _ -> + users = get_notified_from_activity(activity) + notifications = Enum.map(users, fn user -> create_notification(activity, user) end) + {:ok, notifications} + end + end + + def create_notifications(%Activity{data: %{"to" => _, "type" => type}} = activity) + when type in ["Like", "Announce", "Follow"] do + notifications = + activity + |> get_notified_from_activity() + |> Enum.map(&create_notification(activity, &1)) + + {:ok, notifications} + end + + def create_notifications(_), do: {:ok, []} + + # TODO move to sql, too. + def create_notification(%Activity{} = activity, %User{} = user) do + unless skip?(activity, user) do + notification = %SubscriptionNotification{user_id: user.id, activity: activity} + {:ok, notification} = Repo.insert(notification) + Streamer.stream("user", notification) + Streamer.stream("user:subscription_notification", notification) + Push.send(notification) + notification + end + end + + def get_notified_from_activity(activity, local_only \\ true) + + def get_notified_from_activity( + %Activity{data: %{"to" => _, "type" => type} = _data} = activity, + local_only + ) + when type in ["Create", "Like", "Announce", "Follow"] do + [] + |> Utils.maybe_notify_subscribers(activity) + |> Enum.uniq() + |> User.get_users_from_set(local_only) + end + + def get_notified_from_activity(_, _local_only), do: [] + + @spec skip?(Activity.t(), User.t()) :: boolean() + def skip?(activity, user) do + [ + :self, + :followers, + :follows, + :non_followers, + :non_follows, + :recently_followed + ] + |> Enum.any?(&skip?(&1, activity, user)) + end + + @spec skip?(atom(), Activity.t(), User.t()) :: boolean() + def skip?(:self, activity, user) do + activity.data["actor"] == user.ap_id + end + + def skip?( + :followers, + %{data: %{"actor" => actor}}, + %{info: %{notification_settings: %{"followers" => false}}} = user + ) do + actor + |> User.get_cached_by_ap_id() + |> User.following?(user) + end + + def skip?( + :non_followers, + activity, + %{info: %{notification_settings: %{"non_followers" => false}}} = user + ) do + actor = activity.data["actor"] + follower = User.get_cached_by_ap_id(actor) + !User.following?(follower, user) + end + + def skip?(:follows, activity, %{info: %{notification_settings: %{"follows" => false}}} = user) do + actor = activity.data["actor"] + followed = User.get_cached_by_ap_id(actor) + User.following?(user, followed) + end + + def skip?( + :non_follows, + activity, + %{info: %{notification_settings: %{"non_follows" => false}}} = user + ) do + actor = activity.data["actor"] + followed = User.get_cached_by_ap_id(actor) + !User.following?(user, followed) + end + + def skip?(:recently_followed, %{data: %{"type" => "Follow", "actor" => actor}}, user) do + user + |> SubscriptionNotification.for_user() + |> Enum.any?(&match?(%{activity: %{data: %{"type" => "Follow", "actor" => ^actor}}}, &1)) + end + + def skip?(_, _, _), do: false +end diff --git a/lib/pleroma/web/activity_pub/activity_pub.ex b/lib/pleroma/web/activity_pub/activity_pub.ex index 8d0a57623..7e83e27e5 100644 --- a/lib/pleroma/web/activity_pub/activity_pub.ex +++ b/lib/pleroma/web/activity_pub/activity_pub.ex @@ -13,6 +13,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do alias Pleroma.Object.Fetcher alias Pleroma.Pagination alias Pleroma.Repo + alias Pleroma.SubscriptionNotification alias Pleroma.Upload alias Pleroma.User alias Pleroma.Web.ActivityPub.MRF @@ -151,6 +152,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do BackgroundWorker.enqueue("fetch_data_for_activity", %{"activity_id" => activity.id}) Notification.create_notifications(activity) + SubscriptionNotification.create_notifications(activity) participations = activity diff --git a/lib/pleroma/web/pleroma_api/controllers/subscription_notification_controller.ex b/lib/pleroma/web/pleroma_api/controllers/subscription_notification_controller.ex new file mode 100644 index 000000000..37c2222de --- /dev/null +++ b/lib/pleroma/web/pleroma_api/controllers/subscription_notification_controller.ex @@ -0,0 +1,71 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.Web.PleromaAPI.SubscriptionNotificationController do + use Pleroma.Web, :controller + + import Pleroma.Web.ControllerHelper, only: [add_link_headers: 2] + + alias Pleroma.Activity + alias Pleroma.SubscriptionNotification + alias Pleroma.User + alias Pleroma.Web.PleromaAPI.PleromaAPI + + def index(%{assigns: %{user: user}} = conn, params) do + notifications = + user + |> PleromaAPI.get_subscription_notifications(params) + |> Enum.map(&build_notification_data/1) + + conn + |> add_link_headers(notifications) + |> render("index.json", %{notifications: notifications, for: user}) + end + + def show(%{assigns: %{user: user}} = conn, %{"id" => id} = _params) do + with {:ok, notification} <- SubscriptionNotification.get(user, id) do + render(conn, "show.json", %{ + subscription_notification: build_notification_data(notification), + for: user + }) + else + {:error, reason} -> + conn + |> put_status(:forbidden) + |> json(%{"error" => reason}) + end + end + + def clear(%{assigns: %{user: user}} = conn, _params) do + SubscriptionNotification.clear(user) + json(conn, %{}) + end + + def dismiss(%{assigns: %{user: user}} = conn, %{"id" => id} = _params) do + with {:ok, _notif} <- SubscriptionNotification.dismiss(user, id) do + json(conn, %{}) + else + {:error, reason} -> + conn + |> put_status(:forbidden) + |> json(%{"error" => reason}) + end + end + + def destroy_multiple( + %{assigns: %{user: user}} = conn, + %{"ids" => ids} = _params + ) do + SubscriptionNotification.destroy_multiple(user, ids) + json(conn, %{}) + end + + defp build_notification_data(%{activity: %{data: data}} = notification) do + %{ + notification: notification, + actor: User.get_cached_by_ap_id(data["actor"]), + parent_activity: Activity.get_create_by_object_ap_id(data["object"]) + } + end +end diff --git a/lib/pleroma/web/pleroma_api/pleroma_api.ex b/lib/pleroma/web/pleroma_api/pleroma_api.ex new file mode 100644 index 000000000..480964845 --- /dev/null +++ b/lib/pleroma/web/pleroma_api/pleroma_api.ex @@ -0,0 +1,40 @@ +defmodule Pleroma.Web.PleromaAPI.PleromaAPI do + import Ecto.Query + import Ecto.Changeset + + alias Pleroma.Activity + alias Pleroma.Pagination + alias Pleroma.SubscriptionNotification + + def get_subscription_notifications(user, params \\ %{}) do + options = cast_params(params) + + user + |> SubscriptionNotification.for_user_query(options) + |> restrict(:exclude_types, options) + |> Pagination.fetch_paginated(params) + end + + defp cast_params(params) do + param_types = %{ + exclude_types: {:array, :string}, + reblogs: :boolean, + with_muted: :boolean + } + + changeset = cast({%{}, param_types}, params, Map.keys(param_types)) + changeset.changes + end + + defp restrict(query, :exclude_types, %{exclude_types: mastodon_types = [_ | _]}) do + ap_types = + mastodon_types + |> Enum.map(&Activity.from_mastodon_notification_type/1) + |> Enum.filter(& &1) + + query + |> where([q, a], not fragment("? @> ARRAY[?->>'type']::varchar[]", ^ap_types, a.data)) + end + + defp restrict(query, _, _), do: query +end diff --git a/lib/pleroma/web/pleroma_api/views/subscription_notification_view.ex b/lib/pleroma/web/pleroma_api/views/subscription_notification_view.ex new file mode 100644 index 000000000..0eccbcbb9 --- /dev/null +++ b/lib/pleroma/web/pleroma_api/views/subscription_notification_view.ex @@ -0,0 +1,61 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.Web.PleromaAPI.SubscriptionNotificationView do + use Pleroma.Web, :view + + alias Pleroma.Activity + alias Pleroma.Web.CommonAPI + alias Pleroma.Web.MastodonAPI.AccountView + alias Pleroma.Web.MastodonAPI.StatusView + alias Pleroma.Web.PleromaAPI.SubscriptionNotificationView + + def render("index.json", %{notifications: notifications, for: user}) do + safe_render_many(notifications, SubscriptionNotificationView, "show.json", %{for: user}) + end + + def render("show.json", %{ + subscription_notification: %{ + notification: %{activity: activity} = notification, + actor: actor, + parent_activity: parent_activity + }, + for: user + }) do + mastodon_type = Activity.mastodon_notification_type(activity) + + response = %{ + id: to_string(notification.id), + type: mastodon_type, + created_at: CommonAPI.Utils.to_masto_date(notification.inserted_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}) + }) + + "favourite" -> + response + |> Map.merge(%{ + status: StatusView.render("status.json", %{activity: parent_activity, for: user}) + }) + + "reblog" -> + response + |> Map.merge(%{ + status: StatusView.render("status.json", %{activity: parent_activity, for: user}) + }) + + "follow" -> + response + + _ -> + nil + end + end +end diff --git a/lib/pleroma/web/push/impl.ex b/lib/pleroma/web/push/impl.ex index 35d3ff07c..7ea5607fa 100644 --- a/lib/pleroma/web/push/impl.ex +++ b/lib/pleroma/web/push/impl.ex @@ -9,6 +9,7 @@ defmodule Pleroma.Web.Push.Impl do alias Pleroma.Notification alias Pleroma.Object alias Pleroma.Repo + alias Pleroma.SubscriptionNotification alias Pleroma.User alias Pleroma.Web.Metadata.Utils alias Pleroma.Web.Push.Subscription @@ -19,7 +20,7 @@ defmodule Pleroma.Web.Push.Impl do @types ["Create", "Follow", "Announce", "Like"] @doc "Performs sending notifications for user subscriptions" - @spec perform(Notification.t()) :: list(any) | :error + @spec perform(Notification.t() | SubscriptionNotification.t()) :: list(any) | :error def perform( %{ activity: %{data: %{"type" => activity_type}, id: activity_id} = activity, diff --git a/lib/pleroma/web/router.ex b/lib/pleroma/web/router.ex index 7a20b6d75..8bf55631e 100644 --- a/lib/pleroma/web/router.ex +++ b/lib/pleroma/web/router.ex @@ -293,6 +293,14 @@ defmodule Pleroma.Web.Router do pipe_through(:oauth_read) get("/conversations/:id/statuses", PleromaAPIController, :conversation_statuses) get("/conversations/:id", PleromaAPIController, :conversation) + + scope "/subscription_notifications" do + post("/clear", SubscriptionNotificationController, :clear) + post("/dismiss", SubscriptionNotificationController, :dismiss) + delete("/destroy_multiple", SubscriptionNotificationController, :destroy_multiple) + get("/", SubscriptionNotificationController, :index) + get("/:id", SubscriptionNotificationController, :show) + end end scope [] do diff --git a/priv/repo/migrations/20190824195028_create_subscription_notifications.exs b/priv/repo/migrations/20190824195028_create_subscription_notifications.exs new file mode 100644 index 000000000..fcceb4386 --- /dev/null +++ b/priv/repo/migrations/20190824195028_create_subscription_notifications.exs @@ -0,0 +1,15 @@ +defmodule Pleroma.Repo.Migrations.CreateSubscriptionNotifications do + use Ecto.Migration + + def change do + create_if_not_exists table(:subscription_notifications) do + add(:user_id, references(:users, type: :uuid, on_delete: :delete_all)) + add(:activity_id, references(:activities, type: :uuid, on_delete: :delete_all)) + + timestamps() + end + + create_if_not_exists(index(:subscription_notifications, [:user_id])) + create_if_not_exists(index(:subscription_notifications, ["id desc nulls last"])) + end +end diff --git a/test/notification_test.exs b/test/notification_test.exs index 54c0f9877..1dbad34c1 100644 --- a/test/notification_test.exs +++ b/test/notification_test.exs @@ -33,16 +33,16 @@ defmodule Pleroma.NotificationTest do assert other_notification.activity_id == activity.id end - test "it creates a notification for subscribed users" do + test "it does not create a notification for subscribed users" do user = insert(:user) subscriber = insert(:user) User.subscribe(subscriber, user) {:ok, status} = CommonAPI.post(user, %{"status" => "Akariiiin"}) - {:ok, [notification]} = Notification.create_notifications(status) + {:ok, notifications} = Notification.create_notifications(status) - assert notification.user_id == subscriber.id + assert notifications == [] end test "does not create a notification for subscribed users if status is a reply" do @@ -182,14 +182,16 @@ defmodule Pleroma.NotificationTest do refute Notification.create_notification(activity_dupe, followed_user) end - test "it doesn't create duplicate notifications for follow+subscribed users" do + test "it doesn't create notifications for follow+subscribed users" do user = insert(:user) subscriber = insert(:user) {:ok, _, _, _} = CommonAPI.follow(subscriber, user) User.subscribe(subscriber, user) {:ok, status} = CommonAPI.post(user, %{"status" => "Akariiiin"}) - {:ok, [_notif]} = Notification.create_notifications(status) + {:ok, notifications} = Notification.create_notifications(status) + + assert notifications == [] end test "it doesn't create subscription notifications if the recipient cannot see the status" do diff --git a/test/web/mastodon_api/mastodon_api_test.exs b/test/web/mastodon_api/mastodon_api_test.exs index 7fcb2bd55..848fce7ad 100644 --- a/test/web/mastodon_api/mastodon_api_test.exs +++ b/test/web/mastodon_api/mastodon_api_test.exs @@ -75,9 +75,9 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPITest do User.subscribe(subscriber, user) - {:ok, status} = CommonAPI.post(user, %{"status" => "Akariiiin"}) + {:ok, status} = CommonAPI.post(user, %{"status" => "Akariiiin @#{subscriber.nickname}"}) - {:ok, status1} = CommonAPI.post(user, %{"status" => "Magi"}) + {:ok, status1} = CommonAPI.post(user, %{"status" => "Magi @#{subscriber.nickname}"}) {:ok, [notification]} = Notification.create_notifications(status) {:ok, [notification1]} = Notification.create_notifications(status1) res = MastodonAPI.get_notifications(subscriber) diff --git a/test/web/pleroma_api/pleroma_api_controller_test.exs b/test/web/pleroma_api/controllers/pleroma_api_controller_test.exs index 7eaeda4a0..7eaeda4a0 100644 --- a/test/web/pleroma_api/pleroma_api_controller_test.exs +++ b/test/web/pleroma_api/controllers/pleroma_api_controller_test.exs diff --git a/test/web/pleroma_api/controllers/subscription_notification_controller_test.exs b/test/web/pleroma_api/controllers/subscription_notification_controller_test.exs new file mode 100644 index 000000000..c6a71732d --- /dev/null +++ b/test/web/pleroma_api/controllers/subscription_notification_controller_test.exs @@ -0,0 +1,234 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.Web.PleromaAPI.SubscriptionNotificationControllerTest do + use Pleroma.Web.ConnCase + + alias Pleroma.Repo + alias Pleroma.SubscriptionNotification + alias Pleroma.User + alias Pleroma.Web.CommonAPI + import Pleroma.Factory + import Tesla.Mock + + setup do + mock(fn env -> apply(HttpRequestMock, :request, [env]) end) + :ok + end + + clear_config([:instance, :public]) + clear_config([:rich_media, :enabled]) + + describe "subscription_notifications" do + setup do + user = insert(:user) + subscriber = insert(:user) + + User.subscribe(subscriber, user) + + {:ok, %{user: user, subscriber: subscriber}} + end + + test "list of notifications", %{conn: conn, user: user, subscriber: subscriber} do + status_text = "Hello" + {:ok, _activity} = CommonAPI.post(user, %{"status" => status_text}) + path = subscription_notification_path(conn, :index) + + conn = + conn + |> assign(:user, subscriber) + |> get(path) + + assert [%{"status" => %{"content" => response}} | _rest] = json_response(conn, 200) + assert response == status_text + end + + test "getting a single notification", %{conn: conn, user: user, subscriber: subscriber} do + status_text = "Hello" + + {:ok, _activity} = CommonAPI.post(user, %{"status" => status_text}) + [notification] = Repo.all(SubscriptionNotification) + + path = subscription_notification_path(conn, :show, notification) + + conn = + conn + |> assign(:user, subscriber) + |> get(path) + + assert %{"status" => %{"content" => response}} = json_response(conn, 200) + assert response == status_text + end + + test "dismissing a single notification also deletes it", %{ + conn: conn, + user: user, + subscriber: subscriber + } do + status_text = "Hello" + {:ok, _activity} = CommonAPI.post(user, %{"status" => status_text}) + + [notification] = Repo.all(SubscriptionNotification) + + conn = + conn + |> assign(:user, subscriber) + |> post(subscription_notification_path(conn, :dismiss), %{"id" => notification.id}) + + assert %{} = json_response(conn, 200) + + assert Repo.all(SubscriptionNotification) == [] + end + + test "clearing all notifications also deletes them", %{ + conn: conn, + user: user, + subscriber: subscriber + } do + status_text1 = "Hello" + status_text2 = "Hello again" + {:ok, _activity1} = CommonAPI.post(user, %{"status" => status_text1}) + {:ok, _activity2} = CommonAPI.post(user, %{"status" => status_text2}) + + conn = + conn + |> assign(:user, subscriber) + |> post(subscription_notification_path(conn, :clear)) + + assert %{} = json_response(conn, 200) + + conn = + build_conn() + |> assign(:user, subscriber) + |> get(subscription_notification_path(conn, :index)) + + assert json_response(conn, 200) == [] + + assert Repo.all(SubscriptionNotification) == [] + end + + test "paginates notifications using min_id, since_id, max_id, and limit", %{ + conn: conn, + user: user, + subscriber: subscriber + } do + {:ok, activity1} = CommonAPI.post(user, %{"status" => "Hello 1"}) + {:ok, activity2} = CommonAPI.post(user, %{"status" => "Hello 2"}) + {:ok, activity3} = CommonAPI.post(user, %{"status" => "Hello 3"}) + {:ok, activity4} = CommonAPI.post(user, %{"status" => "Hello 4"}) + + notification1_id = + Repo.get_by(SubscriptionNotification, activity_id: activity1.id).id |> to_string() + + notification2_id = + Repo.get_by(SubscriptionNotification, activity_id: activity2.id).id |> to_string() + + notification3_id = + Repo.get_by(SubscriptionNotification, activity_id: activity3.id).id |> to_string() + + notification4_id = + Repo.get_by(SubscriptionNotification, activity_id: activity4.id).id |> to_string() + + conn = assign(conn, :user, subscriber) + + # min_id + conn_res = + get( + conn, + subscription_notification_path(conn, :index, %{ + "limit" => 2, + "min_id" => notification1_id + }) + ) + + result = json_response(conn_res, 200) + assert [%{"id" => ^notification3_id}, %{"id" => ^notification2_id}] = result + + # since_id + conn_res = + get( + conn, + subscription_notification_path(conn, :index, %{ + "limit" => 2, + "since_id" => notification1_id + }) + ) + + result = json_response(conn_res, 200) + assert [%{"id" => ^notification4_id}, %{"id" => ^notification3_id}] = result + + # max_id + conn_res = + get( + conn, + subscription_notification_path(conn, :index, %{ + "limit" => 2, + "max_id" => notification4_id + }) + ) + + result = json_response(conn_res, 200) + assert [%{"id" => ^notification3_id}, %{"id" => ^notification2_id}] = result + end + + test "destroy multiple", %{conn: conn, user: user1, subscriber: user2} do + # mutual subscription + User.subscribe(user1, user2) + + {:ok, activity1} = CommonAPI.post(user1, %{"status" => "Hello 1"}) + {:ok, activity2} = CommonAPI.post(user1, %{"status" => "World 1"}) + {:ok, activity3} = CommonAPI.post(user2, %{"status" => "Hello 2"}) + {:ok, activity4} = CommonAPI.post(user2, %{"status" => "World 2"}) + + notification1_id = + Repo.get_by(SubscriptionNotification, activity_id: activity1.id).id |> to_string() + + notification2_id = + Repo.get_by(SubscriptionNotification, activity_id: activity2.id).id |> to_string() + + notification3_id = + Repo.get_by(SubscriptionNotification, activity_id: activity3.id).id |> to_string() + + notification4_id = + Repo.get_by(SubscriptionNotification, activity_id: activity4.id).id |> to_string() + + conn = assign(conn, :user, user1) + + conn_res = get(conn, subscription_notification_path(conn, :index)) + + result = json_response(conn_res, 200) + + Enum.each(result, fn %{"id" => id} -> + assert id in [notification3_id, notification4_id] + end) + + conn2 = assign(conn, :user, user2) + + conn_res = get(conn2, subscription_notification_path(conn, :index)) + + result = json_response(conn_res, 200) + + Enum.each(result, fn %{"id" => id} -> + assert id in [notification1_id, notification2_id] + end) + + conn_destroy = + delete(conn, subscription_notification_path(conn, :destroy_multiple), %{ + "ids" => [notification3_id, notification4_id] + }) + + assert json_response(conn_destroy, 200) == %{} + + conn_res = get(conn2, subscription_notification_path(conn, :index)) + + result = json_response(conn_res, 200) + + Enum.each(result, fn %{"id" => id} -> + assert id in [notification1_id, notification2_id] + end) + + assert length(Repo.all(SubscriptionNotification)) == 2 + end + end +end |