First
[anni] / priv / repo / migrations / 20190109152453_add_visibility_function.exs
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Repo.Migrations.AddVisibilityFunction do
6   use Ecto.Migration
7   @disable_ddl_transaction true
8
9   def up do
10     definition = """
11     create or replace function activity_visibility(actor varchar, recipients varchar[], data jsonb) returns varchar as $$
12     DECLARE
13       fa varchar;
14       public varchar := 'https://www.w3.org/ns/activitystreams#Public';
15     BEGIN
16       SELECT COALESCE(users.follower_address, '') into fa from users where users.ap_id = actor;
17
18       IF data->'to' ? public THEN
19         RETURN 'public';
20       ELSIF data->'cc' ? public THEN
21         RETURN 'unlisted';
22       ELSIF ARRAY[fa] && recipients THEN
23         RETURN 'private';
24       ELSIF not(ARRAY[fa, public] && recipients) THEN
25         RETURN 'direct';
26       ELSE
27         RETURN 'unknown';
28       END IF;
29     END;
30     $$ LANGUAGE plpgsql IMMUTABLE;
31     """
32
33     execute(definition)
34
35     create(
36       index(:activities, ["activity_visibility(actor, recipients, data)"],
37         name: :activities_visibility_index,
38         concurrently: true
39       )
40     )
41   end
42
43   def down do
44     drop_if_exists(
45       index(:activities, ["activity_visibility(actor, recipients, data)"],
46         name: :activities_visibility_index
47       )
48     )
49
50     execute(
51       "drop function if exists activity_visibility(actor varchar, recipients varchar[], data jsonb)"
52     )
53   end
54 end