Merge branch 'weblate-pleroma-pleroma' into 'develop'
[akkoma] / lib / pleroma / activity / 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.Activity.Search do
6 alias Pleroma.Activity
7 alias Pleroma.Object.Fetcher
8 alias Pleroma.Pagination
9 alias Pleroma.User
10 alias Pleroma.Web.ActivityPub.Visibility
11
12 require Pleroma.Constants
13
14 import Ecto.Query
15
16 def search(user, search_query, options \\ []) do
17 index_type = if Pleroma.Config.get([:database, :rum_enabled]), do: :rum, else: :gin
18 limit = Enum.min([Keyword.get(options, :limit), 40])
19 offset = Keyword.get(options, :offset, 0)
20 author = Keyword.get(options, :author)
21
22 Activity
23 |> Activity.with_preloaded_object()
24 |> Activity.restrict_deactivated_users()
25 |> restrict_public()
26 |> query_with(index_type, search_query)
27 |> maybe_restrict_local(user)
28 |> maybe_restrict_author(author)
29 |> maybe_restrict_blocked(user)
30 |> Pagination.fetch_paginated(
31 %{"offset" => offset, "limit" => limit, "skip_order" => index_type == :rum},
32 :offset
33 )
34 |> maybe_fetch(user, search_query)
35 end
36
37 def maybe_restrict_author(query, %User{} = author) do
38 Activity.Queries.by_author(query, author)
39 end
40
41 def maybe_restrict_author(query, _), do: query
42
43 def maybe_restrict_blocked(query, %User{} = user) do
44 Activity.Queries.exclude_authors(query, User.blocked_users_ap_ids(user))
45 end
46
47 def maybe_restrict_blocked(query, _), do: query
48
49 defp restrict_public(q) do
50 from([a, o] in q,
51 where: fragment("?->>'type' = 'Create'", a.data),
52 where: ^Pleroma.Constants.as_public() in a.recipients
53 )
54 end
55
56 defp query_with(q, :gin, search_query) do
57 from([a, o] in q,
58 where:
59 fragment(
60 "to_tsvector('english', ?->>'content') @@ plainto_tsquery('english', ?)",
61 o.data,
62 ^search_query
63 )
64 )
65 end
66
67 defp query_with(q, :rum, search_query) do
68 from([a, o] in q,
69 where:
70 fragment(
71 "? @@ plainto_tsquery('english', ?)",
72 o.fts_content,
73 ^search_query
74 ),
75 order_by: [fragment("? <=> now()::date", o.inserted_at)]
76 )
77 end
78
79 defp maybe_restrict_local(q, user) do
80 limit = Pleroma.Config.get([:instance, :limit_to_local_content], :unauthenticated)
81
82 case {limit, user} do
83 {:all, _} -> restrict_local(q)
84 {:unauthenticated, %User{}} -> q
85 {:unauthenticated, _} -> restrict_local(q)
86 {false, _} -> q
87 end
88 end
89
90 defp restrict_local(q), do: where(q, local: true)
91
92 defp maybe_fetch(activities, user, search_query) do
93 with true <- Regex.match?(~r/https?:/, search_query),
94 {:ok, object} <- Fetcher.fetch_object_from_id(search_query),
95 %Activity{} = activity <- Activity.get_create_by_object_ap_id(object.data["id"]),
96 true <- Visibility.visible_for_user?(activity, user) do
97 [activity | activities]
98 else
99 _ -> activities
100 end
101 end
102 end