Merge branch 'feature/update-description-for-frontends-setting' into 'develop'
[akkoma] / lib / pleroma / user / search.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.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_discoverable_users()
89 |> filter_internal_users()
90 |> filter_blocked_domains(for_user)
91 |> fts_search(query_string)
92 |> select_top_users(top_user_ids)
93 |> trigram_rank(query_string)
94 |> boost_search_rank(for_user, top_user_ids)
95 |> subquery()
96 |> order_by(desc: :search_rank)
97 |> maybe_restrict_local(for_user)
98 end
99
100 defp select_top_users(query, top_user_ids) do
101 from(u in query,
102 or_where: u.id in ^top_user_ids
103 )
104 end
105
106 defp fts_search(query, query_string) do
107 query_string = to_tsquery(query_string)
108
109 from(
110 u in query,
111 where:
112 fragment(
113 # The fragment must _exactly_ match `users_fts_index`, otherwise the index won't work
114 """
115 (
116 setweight(to_tsvector('simple', regexp_replace(?, '\\W', ' ', 'g')), 'A') ||
117 setweight(to_tsvector('simple', regexp_replace(coalesce(?, ''), '\\W', ' ', 'g')), 'B')
118 ) @@ to_tsquery('simple', ?)
119 """,
120 u.nickname,
121 u.name,
122 ^query_string
123 )
124 )
125 end
126
127 defp to_tsquery(query_string) do
128 String.trim_trailing(query_string, "@" <> local_domain())
129 |> String.replace(~r/[!-\/|@|[-`|{-~|:-?]+/, " ")
130 |> String.trim()
131 |> String.split()
132 |> Enum.map(&(&1 <> ":*"))
133 |> Enum.join(" | ")
134 end
135
136 # Considers nickname match, localized nickname match, name match; preferences nickname match
137 defp trigram_rank(query, query_string) do
138 from(
139 u in query,
140 select_merge: %{
141 search_rank:
142 fragment(
143 """
144 similarity(?, ?) +
145 similarity(?, regexp_replace(?, '@.+', '')) +
146 similarity(?, trim(coalesce(?, '')))
147 """,
148 ^query_string,
149 u.nickname,
150 ^query_string,
151 u.nickname,
152 ^query_string,
153 u.name
154 )
155 }
156 )
157 end
158
159 defp base_query(%User{} = user, true), do: User.get_friends_query(user)
160 defp base_query(_user, _following), do: User
161
162 defp filter_invisible_users(query) do
163 from(q in query, where: q.invisible == false)
164 end
165
166 defp filter_discoverable_users(query) do
167 from(q in query, where: q.discoverable == true)
168 end
169
170 defp filter_internal_users(query) do
171 from(q in query, where: q.actor_type != "Application")
172 end
173
174 defp filter_blocked_user(query, %User{} = blocker) do
175 query
176 |> join(:left, [u], b in Pleroma.UserRelationship,
177 as: :blocks,
178 on: b.relationship_type == ^:block and b.source_id == ^blocker.id and u.id == b.target_id
179 )
180 |> where([blocks: b], is_nil(b.target_id))
181 end
182
183 defp filter_blocked_user(query, _), do: query
184
185 defp filter_blocked_domains(query, %User{domain_blocks: domain_blocks})
186 when length(domain_blocks) > 0 do
187 domains = Enum.join(domain_blocks, ",")
188
189 from(
190 q in query,
191 where: fragment("substring(ap_id from '.*://([^/]*)') NOT IN (?)", ^domains)
192 )
193 end
194
195 defp filter_blocked_domains(query, _), do: query
196
197 defp maybe_resolve(true, user, query) do
198 case {limit(), user} do
199 {:all, _} -> :noop
200 {:unauthenticated, %User{}} -> User.get_or_fetch(query)
201 {:unauthenticated, _} -> :noop
202 {false, _} -> User.get_or_fetch(query)
203 end
204 end
205
206 defp maybe_resolve(_, _, _), do: :noop
207
208 defp maybe_restrict_local(q, user) do
209 case {limit(), user} do
210 {:all, _} -> restrict_local(q)
211 {:unauthenticated, %User{}} -> q
212 {:unauthenticated, _} -> restrict_local(q)
213 {false, _} -> q
214 end
215 end
216
217 defp limit, do: Pleroma.Config.get([:instance, :limit_to_local_content], :unauthenticated)
218
219 defp restrict_local(q), do: where(q, [u], u.local == true)
220
221 defp local_domain, do: Pleroma.Config.get([Pleroma.Web.Endpoint, :url, :host])
222
223 defp boost_search_rank(query, %User{} = for_user, top_user_ids) do
224 friends_ids = User.get_friends_ids(for_user)
225 followers_ids = User.get_followers_ids(for_user)
226
227 from(u in subquery(query),
228 select_merge: %{
229 search_rank:
230 fragment(
231 """
232 CASE WHEN (?) THEN (?) * 1.5
233 WHEN (?) THEN (?) * 1.3
234 WHEN (?) THEN (?) * 1.1
235 WHEN (?) THEN 9001
236 ELSE (?) END
237 """,
238 u.id in ^friends_ids and u.id in ^followers_ids,
239 u.search_rank,
240 u.id in ^friends_ids,
241 u.search_rank,
242 u.id in ^followers_ids,
243 u.search_rank,
244 u.id in ^top_user_ids,
245 u.search_rank
246 )
247 }
248 )
249 end
250
251 defp boost_search_rank(query, _for_user, top_user_ids) do
252 from(u in subquery(query),
253 select_merge: %{
254 search_rank:
255 fragment(
256 """
257 CASE WHEN (?) THEN 9001
258 ELSE (?) END
259 """,
260 u.id in ^top_user_ids,
261 u.search_rank
262 )
263 }
264 )
265 end
266 end