Merge branch 'develop' of git.pleroma.social:pleroma/pleroma into issue/2115
[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.Pagination
7 alias Pleroma.User
8 import Ecto.Query
9
10 @limit 20
11
12 def search(query_string, opts \\ []) do
13 resolve = Keyword.get(opts, :resolve, false)
14 following = Keyword.get(opts, :following, false)
15 result_limit = Keyword.get(opts, :limit, @limit)
16 offset = Keyword.get(opts, :offset, 0)
17
18 for_user = Keyword.get(opts, :for_user)
19
20 query_string = format_query(query_string)
21
22 maybe_resolve(resolve, for_user, query_string)
23
24 results =
25 query_string
26 |> search_query(for_user, following)
27 |> Pagination.fetch_paginated(%{"offset" => offset, "limit" => result_limit}, :offset)
28
29 results
30 end
31
32 defp format_query(query_string) do
33 # Strip the beginning @ off if there is a query
34 query_string = String.trim_leading(query_string, "@")
35
36 with [name, domain] <- String.split(query_string, "@") do
37 encoded_domain =
38 domain
39 |> String.replace(~r/[!-\-|@|[-`|{-~|\/|:|\s]+/, "")
40 |> String.to_charlist()
41 |> :idna.encode()
42 |> to_string()
43
44 name <> "@" <> encoded_domain
45 else
46 _ -> query_string
47 end
48 end
49
50 defp search_query(query_string, for_user, following) do
51 for_user
52 |> base_query(following)
53 |> filter_blocked_user(for_user)
54 |> filter_invisible_users()
55 |> filter_discoverable_users()
56 |> filter_internal_users()
57 |> filter_blocked_domains(for_user)
58 |> fts_search(query_string)
59 |> trigram_rank(query_string)
60 |> boost_search_rank(for_user)
61 |> subquery()
62 |> order_by(desc: :search_rank)
63 |> maybe_restrict_local(for_user)
64 end
65
66 defp fts_search(query, query_string) do
67 query_string = to_tsquery(query_string)
68
69 from(
70 u in query,
71 where:
72 fragment(
73 # The fragment must _exactly_ match `users_fts_index`, otherwise the index won't work
74 """
75 (
76 setweight(to_tsvector('simple', regexp_replace(?, '\\W', ' ', 'g')), 'A') ||
77 setweight(to_tsvector('simple', regexp_replace(coalesce(?, ''), '\\W', ' ', 'g')), 'B')
78 ) @@ to_tsquery('simple', ?)
79 """,
80 u.nickname,
81 u.name,
82 ^query_string
83 )
84 )
85 end
86
87 defp to_tsquery(query_string) do
88 String.trim_trailing(query_string, "@" <> local_domain())
89 |> String.replace(~r/[!-\/|@|[-`|{-~|:-?]+/, " ")
90 |> String.trim()
91 |> String.split()
92 |> Enum.map(&(&1 <> ":*"))
93 |> Enum.join(" | ")
94 end
95
96 # Considers nickname match, localized nickname match, name match; preferences nickname match
97 defp trigram_rank(query, query_string) do
98 from(
99 u in query,
100 select_merge: %{
101 search_rank:
102 fragment(
103 """
104 similarity(?, ?) +
105 similarity(?, regexp_replace(?, '@.+', '')) +
106 similarity(?, trim(coalesce(?, '')))
107 """,
108 ^query_string,
109 u.nickname,
110 ^query_string,
111 u.nickname,
112 ^query_string,
113 u.name
114 )
115 }
116 )
117 end
118
119 defp base_query(%User{} = user, true), do: User.get_friends_query(user)
120 defp base_query(_user, _following), do: User
121
122 defp filter_invisible_users(query) do
123 from(q in query, where: q.invisible == false)
124 end
125
126 defp filter_discoverable_users(query) do
127 from(q in query, where: q.discoverable == true)
128 end
129
130 defp filter_internal_users(query) do
131 from(q in query, where: q.actor_type != "Application")
132 end
133
134 defp filter_blocked_user(query, %User{} = blocker) do
135 query
136 |> join(:left, [u], b in Pleroma.UserRelationship,
137 as: :blocks,
138 on: b.relationship_type == ^:block and b.source_id == ^blocker.id and u.id == b.target_id
139 )
140 |> where([blocks: b], is_nil(b.target_id))
141 end
142
143 defp filter_blocked_user(query, _), do: query
144
145 defp filter_blocked_domains(query, %User{domain_blocks: domain_blocks})
146 when length(domain_blocks) > 0 do
147 domains = Enum.join(domain_blocks, ",")
148
149 from(
150 q in query,
151 where: fragment("substring(ap_id from '.*://([^/]*)') NOT IN (?)", ^domains)
152 )
153 end
154
155 defp filter_blocked_domains(query, _), do: query
156
157 defp maybe_resolve(true, user, query) do
158 case {limit(), user} do
159 {:all, _} -> :noop
160 {:unauthenticated, %User{}} -> User.get_or_fetch(query)
161 {:unauthenticated, _} -> :noop
162 {false, _} -> User.get_or_fetch(query)
163 end
164 end
165
166 defp maybe_resolve(_, _, _), do: :noop
167
168 defp maybe_restrict_local(q, user) do
169 case {limit(), user} do
170 {:all, _} -> restrict_local(q)
171 {:unauthenticated, %User{}} -> q
172 {:unauthenticated, _} -> restrict_local(q)
173 {false, _} -> q
174 end
175 end
176
177 defp limit, do: Pleroma.Config.get([:instance, :limit_to_local_content], :unauthenticated)
178
179 defp restrict_local(q), do: where(q, [u], u.local == true)
180
181 defp local_domain, do: Pleroma.Config.get([Pleroma.Web.Endpoint, :url, :host])
182
183 defp boost_search_rank(query, %User{} = for_user) do
184 friends_ids = User.get_friends_ids(for_user)
185 followers_ids = User.get_followers_ids(for_user)
186
187 from(u in subquery(query),
188 select_merge: %{
189 search_rank:
190 fragment(
191 """
192 CASE WHEN (?) THEN (?) * 1.5
193 WHEN (?) THEN (?) * 1.3
194 WHEN (?) THEN (?) * 1.1
195 ELSE (?) END
196 """,
197 u.id in ^friends_ids and u.id in ^followers_ids,
198 u.search_rank,
199 u.id in ^friends_ids,
200 u.search_rank,
201 u.id in ^followers_ids,
202 u.search_rank,
203 u.search_rank
204 )
205 }
206 )
207 end
208
209 defp boost_search_rank(query, _for_user), do: query
210 end