Merge branch 'docs_updating' into 'develop'
[akkoma] / lib / pleroma / activity / search.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 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(%{"offset" => offset, "limit" => limit}, :offset)
31 |> maybe_fetch(user, search_query)
32 end
33
34 def maybe_restrict_author(query, %User{} = author) do
35 Activity.Queries.by_author(query, author)
36 end
37
38 def maybe_restrict_author(query, _), do: query
39
40 def maybe_restrict_blocked(query, %User{} = user) do
41 Activity.Queries.exclude_authors(query, User.blocked_users_ap_ids(user))
42 end
43
44 def maybe_restrict_blocked(query, _), do: query
45
46 defp restrict_public(q) do
47 from([a, o] in q,
48 where: fragment("?->>'type' = 'Create'", a.data),
49 where: ^Pleroma.Constants.as_public() in a.recipients
50 )
51 end
52
53 defp query_with(q, :gin, search_query) do
54 from([a, o] in q,
55 where:
56 fragment(
57 "to_tsvector('english', ?->>'content') @@ plainto_tsquery('english', ?)",
58 o.data,
59 ^search_query
60 )
61 )
62 end
63
64 defp query_with(q, :rum, search_query) do
65 from([a, o] in q,
66 where:
67 fragment(
68 "? @@ plainto_tsquery('english', ?)",
69 o.fts_content,
70 ^search_query
71 ),
72 order_by: [fragment("? <=> now()::date", o.inserted_at)]
73 )
74 end
75
76 defp maybe_restrict_local(q, user) do
77 limit = Pleroma.Config.get([:instance, :limit_to_local_content], :unauthenticated)
78
79 case {limit, user} do
80 {:all, _} -> restrict_local(q)
81 {:unauthenticated, %User{}} -> q
82 {:unauthenticated, _} -> restrict_local(q)
83 {false, _} -> q
84 end
85 end
86
87 defp restrict_local(q), do: where(q, local: true)
88
89 defp maybe_fetch(activities, user, search_query) do
90 with true <- Regex.match?(~r/https?:/, search_query),
91 {:ok, object} <- Fetcher.fetch_object_from_id(search_query),
92 %Activity{} = activity <- Activity.get_create_by_object_ap_id(object.data["id"]),
93 true <- Visibility.visible_for_user?(activity, user) do
94 [activity | activities]
95 else
96 _ -> activities
97 end
98 end
99 end