Merge branch 'search-even-more' 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 %User{} = user <- Pleroma.Repo.get_by(User, uri: query) do
58 [user.id | list]
59 else
60 _ -> list
61 end
62 end
63
64 defp format_query(query_string) do
65 # Strip the beginning @ off if there is a query
66 query_string = String.trim_leading(query_string, "@")
67
68 with [name, domain] <- String.split(query_string, "@") do
69 encoded_domain =
70 domain
71 |> String.replace(~r/[!-\-|@|[-`|{-~|\/|:|\s]+/, "")
72 |> String.to_charlist()
73 |> :idna.encode()
74 |> to_string()
75
76 name <> "@" <> encoded_domain
77 else
78 _ -> query_string
79 end
80 end
81
82 defp search_query(query_string, for_user, following, top_user_ids) do
83 for_user
84 |> base_query(following)
85 |> filter_blocked_user(for_user)
86 |> filter_invisible_users()
87 |> filter_discoverable_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_discoverable_users(query) do
166 from(q in query, where: q.discoverable == true)
167 end
168
169 defp filter_internal_users(query) do
170 from(q in query, where: q.actor_type != "Application")
171 end
172
173 defp filter_blocked_user(query, %User{} = blocker) do
174 query
175 |> join(:left, [u], b in Pleroma.UserRelationship,
176 as: :blocks,
177 on: b.relationship_type == ^:block and b.source_id == ^blocker.id and u.id == b.target_id
178 )
179 |> where([blocks: b], is_nil(b.target_id))
180 end
181
182 defp filter_blocked_user(query, _), do: query
183
184 defp filter_blocked_domains(query, %User{domain_blocks: domain_blocks})
185 when length(domain_blocks) > 0 do
186 domains = Enum.join(domain_blocks, ",")
187
188 from(
189 q in query,
190 where: fragment("substring(ap_id from '.*://([^/]*)') NOT IN (?)", ^domains)
191 )
192 end
193
194 defp filter_blocked_domains(query, _), do: query
195
196 defp maybe_resolve(true, user, query) do
197 case {limit(), user} do
198 {:all, _} -> :noop
199 {:unauthenticated, %User{}} -> User.get_or_fetch(query)
200 {:unauthenticated, _} -> :noop
201 {false, _} -> User.get_or_fetch(query)
202 end
203 end
204
205 defp maybe_resolve(_, _, _), do: :noop
206
207 defp maybe_restrict_local(q, user) do
208 case {limit(), user} do
209 {:all, _} -> restrict_local(q)
210 {:unauthenticated, %User{}} -> q
211 {:unauthenticated, _} -> restrict_local(q)
212 {false, _} -> q
213 end
214 end
215
216 defp limit, do: Pleroma.Config.get([:instance, :limit_to_local_content], :unauthenticated)
217
218 defp restrict_local(q), do: where(q, [u], u.local == true)
219
220 defp local_domain, do: Pleroma.Config.get([Pleroma.Web.Endpoint, :url, :host])
221
222 defp boost_search_rank(query, %User{} = for_user, top_user_ids) do
223 friends_ids = User.get_friends_ids(for_user)
224 followers_ids = User.get_followers_ids(for_user)
225
226 from(u in subquery(query),
227 select_merge: %{
228 search_rank:
229 fragment(
230 """
231 CASE WHEN (?) THEN (?) * 1.5
232 WHEN (?) THEN (?) * 1.3
233 WHEN (?) THEN (?) * 1.1
234 WHEN (?) THEN 9001
235 ELSE (?) END
236 """,
237 u.id in ^friends_ids and u.id in ^followers_ids,
238 u.search_rank,
239 u.id in ^friends_ids,
240 u.search_rank,
241 u.id in ^followers_ids,
242 u.search_rank,
243 u.id in ^top_user_ids,
244 u.search_rank
245 )
246 }
247 )
248 end
249
250 defp boost_search_rank(query, _for_user, top_user_ids) do
251 from(u in subquery(query),
252 select_merge: %{
253 search_rank:
254 fragment(
255 """
256 CASE WHEN (?) THEN 9001
257 ELSE (?) END
258 """,
259 u.id in ^top_user_ids,
260 u.search_rank
261 )
262 }
263 )
264 end
265 end