ActivityPub: Handle clashing nicknames for the same ap id
[akkoma] / lib / pleroma / activity / queries.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Activity.Queries do
6 @moduledoc """
7 Contains queries for Activity.
8 """
9
10 import Ecto.Query, only: [from: 2, where: 3]
11
12 @type query :: Ecto.Queryable.t() | Activity.t()
13
14 alias Pleroma.Activity
15 alias Pleroma.User
16
17 @spec by_ap_id(query, String.t()) :: query
18 def by_ap_id(query \\ Activity, ap_id) do
19 from(
20 activity in query,
21 where: fragment("(?)->>'id' = ?", activity.data, ^to_string(ap_id))
22 )
23 end
24
25 @spec by_actor(query, String.t()) :: query
26 def by_actor(query \\ Activity, actor) do
27 from(a in query, where: a.actor == ^actor)
28 end
29
30 @spec by_author(query, User.t()) :: query
31 def by_author(query \\ Activity, %User{ap_id: ap_id}) do
32 from(a in query, where: a.actor == ^ap_id)
33 end
34
35 def find_by_object_ap_id(activities, object_ap_id) do
36 Enum.find(
37 activities,
38 &(object_ap_id in [is_map(&1.data["object"]) && &1.data["object"]["id"], &1.data["object"]])
39 )
40 end
41
42 @spec by_object_id(query, String.t() | [String.t()]) :: query
43 def by_object_id(query \\ Activity, object_id)
44
45 def by_object_id(query, object_ids) when is_list(object_ids) do
46 from(
47 activity in query,
48 where:
49 fragment(
50 "coalesce((?)->'object'->>'id', (?)->>'object') = ANY(?)",
51 activity.data,
52 activity.data,
53 ^object_ids
54 )
55 )
56 end
57
58 def by_object_id(query, object_id) when is_binary(object_id) do
59 from(activity in query,
60 where:
61 fragment(
62 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
63 activity.data,
64 activity.data,
65 ^object_id
66 )
67 )
68 end
69
70 @spec by_object_in_reply_to_id(query, String.t(), keyword()) :: query
71 def by_object_in_reply_to_id(query, in_reply_to_id, opts \\ []) do
72 query =
73 if opts[:skip_preloading] do
74 Activity.with_joined_object(query)
75 else
76 Activity.with_preloaded_object(query)
77 end
78
79 where(
80 query,
81 [activity, object: o],
82 fragment("(?)->>'inReplyTo' = ?", o.data, ^to_string(in_reply_to_id))
83 )
84 end
85
86 @spec by_type(query, String.t()) :: query
87 def by_type(query \\ Activity, activity_type) do
88 from(
89 activity in query,
90 where: fragment("(?)->>'type' = ?", activity.data, ^activity_type)
91 )
92 end
93
94 @spec exclude_type(query, String.t()) :: query
95 def exclude_type(query \\ Activity, activity_type) do
96 from(
97 activity in query,
98 where: fragment("(?)->>'type' != ?", activity.data, ^activity_type)
99 )
100 end
101
102 def exclude_authors(query \\ Activity, actors) do
103 from(activity in query, where: activity.actor not in ^actors)
104 end
105 end