Merge remote-tracking branch 'upstream/develop' into block-behavior
[akkoma] / lib / pleroma / user / search.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.User.Search do
6 alias Pleroma.EctoType.ActivityPub.ObjectValidators.Uri, as: UriType
7 alias Pleroma.Pagination
8 alias Pleroma.User
9
10 import Ecto.Query
11
12 @limit 20
13
14 def search(query_string, opts \\ []) do
15 resolve = Keyword.get(opts, :resolve, false)
16 following = Keyword.get(opts, :following, false)
17 result_limit = Keyword.get(opts, :limit, @limit)
18 offset = Keyword.get(opts, :offset, 0)
19
20 for_user = Keyword.get(opts, :for_user)
21
22 query_string = format_query(query_string)
23
24 # If this returns anything, it should bounce to the top
25 maybe_resolved = maybe_resolve(resolve, for_user, query_string)
26
27 top_user_ids =
28 []
29 |> maybe_add_resolved(maybe_resolved)
30 |> maybe_add_ap_id_match(query_string)
31 |> maybe_add_uri_match(query_string)
32
33 results =
34 query_string
35 |> search_query(for_user, following, top_user_ids)
36 |> Pagination.fetch_paginated(%{"offset" => offset, "limit" => result_limit}, :offset)
37
38 results
39 end
40
41 defp maybe_add_resolved(list, {:ok, %User{} = user}) do
42 [user.id | list]
43 end
44
45 defp maybe_add_resolved(list, _), do: list
46
47 defp maybe_add_ap_id_match(list, query) do
48 if user = User.get_cached_by_ap_id(query) do
49 [user.id | list]
50 else
51 list
52 end
53 end
54
55 defp maybe_add_uri_match(list, query) do
56 with {:ok, query} <- UriType.cast(query),
57 q = from(u in User, where: u.uri == ^query, select: u.id),
58 users = Pleroma.Repo.all(q) do
59 users ++ list
60 else
61 _ -> list
62 end
63 end
64
65 defp format_query(query_string) do
66 # Strip the beginning @ off if there is a query
67 query_string = String.trim_leading(query_string, "@")
68
69 with [name, domain] <- String.split(query_string, "@") do
70 encoded_domain =
71 domain
72 |> String.replace(~r/[!-\-|@|[-`|{-~|\/|:|\s]+/, "")
73 |> String.to_charlist()
74 |> :idna.encode()
75 |> to_string()
76
77 name <> "@" <> encoded_domain
78 else
79 _ -> query_string
80 end
81 end
82
83 defp search_query(query_string, for_user, following, top_user_ids) do
84 for_user
85 |> base_query(following)
86 |> filter_blocked_user(for_user)
87 |> filter_invisible_users()
88 |> filter_internal_users()
89 |> filter_blocked_domains(for_user)
90 |> fts_search(query_string)
91 |> select_top_users(top_user_ids)
92 |> trigram_rank(query_string)
93 |> boost_search_rank(for_user, top_user_ids)
94 |> subquery()
95 |> order_by(desc: :search_rank)
96 |> maybe_restrict_local(for_user)
97 end
98
99 defp select_top_users(query, top_user_ids) do
100 from(u in query,
101 or_where: u.id in ^top_user_ids
102 )
103 end
104
105 defp fts_search(query, query_string) do
106 query_string = to_tsquery(query_string)
107
108 from(
109 u in query,
110 where:
111 fragment(
112 # The fragment must _exactly_ match `users_fts_index`, otherwise the index won't work
113 """
114 (
115 setweight(to_tsvector('simple', regexp_replace(?, '\\W', ' ', 'g')), 'A') ||
116 setweight(to_tsvector('simple', regexp_replace(coalesce(?, ''), '\\W', ' ', 'g')), 'B')
117 ) @@ to_tsquery('simple', ?)
118 """,
119 u.nickname,
120 u.name,
121 ^query_string
122 )
123 )
124 end
125
126 defp to_tsquery(query_string) do
127 String.trim_trailing(query_string, "@" <> local_domain())
128 |> String.replace(~r/[!-\/|@|[-`|{-~|:-?]+/, " ")
129 |> String.trim()
130 |> String.split()
131 |> Enum.map(&(&1 <> ":*"))
132 |> Enum.join(" | ")
133 end
134
135 # Considers nickname match, localized nickname match, name match; preferences nickname match
136 defp trigram_rank(query, query_string) do
137 from(
138 u in query,
139 select_merge: %{
140 search_rank:
141 fragment(
142 """
143 similarity(?, ?) +
144 similarity(?, regexp_replace(?, '@.+', '')) +
145 similarity(?, trim(coalesce(?, '')))
146 """,
147 ^query_string,
148 u.nickname,
149 ^query_string,
150 u.nickname,
151 ^query_string,
152 u.name
153 )
154 }
155 )
156 end
157
158 defp base_query(%User{} = user, true), do: User.get_friends_query(user)
159 defp base_query(_user, _following), do: User
160
161 defp filter_invisible_users(query) do
162 from(q in query, where: q.invisible == false)
163 end
164
165 defp filter_internal_users(query) do
166 from(q in query, where: q.actor_type != "Application")
167 end
168
169 defp filter_blocked_user(query, %User{} = blocker) do
170 query
171 |> join(:left, [u], b in Pleroma.UserRelationship,
172 as: :blocks,
173 on: b.relationship_type == ^:block and b.source_id == ^blocker.id and u.id == b.target_id
174 )
175 |> where([blocks: b], is_nil(b.target_id))
176 end
177
178 defp filter_blocked_user(query, _), do: query
179
180 defp filter_blocked_domains(query, %User{domain_blocks: domain_blocks})
181 when length(domain_blocks) > 0 do
182 domains = Enum.join(domain_blocks, ",")
183
184 from(
185 q in query,
186 where: fragment("substring(ap_id from '.*://([^/]*)') NOT IN (?)", ^domains)
187 )
188 end
189
190 defp filter_blocked_domains(query, _), do: query
191
192 defp maybe_resolve(true, user, query) do
193 case {limit(), user} do
194 {:all, _} -> :noop
195 {:unauthenticated, %User{}} -> User.get_or_fetch(query)
196 {:unauthenticated, _} -> :noop
197 {false, _} -> User.get_or_fetch(query)
198 end
199 end
200
201 defp maybe_resolve(_, _, _), do: :noop
202
203 defp maybe_restrict_local(q, user) do
204 case {limit(), user} do
205 {:all, _} -> restrict_local(q)
206 {:unauthenticated, %User{}} -> q
207 {:unauthenticated, _} -> restrict_local(q)
208 {false, _} -> q
209 end
210 end
211
212 defp limit, do: Pleroma.Config.get([:instance, :limit_to_local_content], :unauthenticated)
213
214 defp restrict_local(q), do: where(q, [u], u.local == true)
215
216 defp local_domain, do: Pleroma.Config.get([Pleroma.Web.Endpoint, :url, :host])
217
218 defp boost_search_rank(query, %User{} = for_user, top_user_ids) do
219 friends_ids = User.get_friends_ids(for_user)
220 followers_ids = User.get_followers_ids(for_user)
221
222 from(u in subquery(query),
223 select_merge: %{
224 search_rank:
225 fragment(
226 """
227 CASE WHEN (?) THEN (?) * 1.5
228 WHEN (?) THEN (?) * 1.3
229 WHEN (?) THEN (?) * 1.1
230 WHEN (?) THEN 9001
231 ELSE (?) END
232 """,
233 u.id in ^friends_ids and u.id in ^followers_ids,
234 u.search_rank,
235 u.id in ^friends_ids,
236 u.search_rank,
237 u.id in ^followers_ids,
238 u.search_rank,
239 u.id in ^top_user_ids,
240 u.search_rank
241 )
242 }
243 )
244 end
245
246 defp boost_search_rank(query, _for_user, top_user_ids) do
247 from(u in subquery(query),
248 select_merge: %{
249 search_rank:
250 fragment(
251 """
252 CASE WHEN (?) THEN 9001
253 ELSE (?) END
254 """,
255 u.id in ^top_user_ids,
256 u.search_rank
257 )
258 }
259 )
260 end
261 end