0cc3770a70a6b13664242a34b0bd52c558321938
[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 import Ecto.Query
13
14 def search(user, search_query, options \\ []) do
15 index_type = if Pleroma.Config.get([:database, :rum_enabled]), do: :rum, else: :gin
16 limit = Enum.min([Keyword.get(options, :limit), 40])
17 offset = Keyword.get(options, :offset, 0)
18 author = Keyword.get(options, :author)
19
20 Activity
21 |> Activity.with_preloaded_object()
22 |> Activity.restrict_deactivated_users()
23 |> restrict_public()
24 |> query_with(index_type, search_query)
25 |> maybe_restrict_local(user)
26 |> maybe_restrict_author(author)
27 |> Pagination.fetch_paginated(%{"offset" => offset, "limit" => limit}, :offset)
28 |> maybe_fetch(user, search_query)
29 end
30
31 def maybe_restrict_author(query, %User{} = author) do
32 from([a, o] in query,
33 where: a.actor == ^author.ap_id
34 )
35 end
36
37 def maybe_restrict_author(query, _), do: query
38
39 defp restrict_public(q) do
40 from([a, o] in q,
41 where: fragment("?->>'type' = 'Create'", a.data),
42 where: "https://www.w3.org/ns/activitystreams#Public" in a.recipients
43 )
44 end
45
46 defp query_with(q, :gin, search_query) do
47 from([a, o] in q,
48 where:
49 fragment(
50 "to_tsvector('english', ?->>'content') @@ plainto_tsquery('english', ?)",
51 o.data,
52 ^search_query
53 )
54 )
55 end
56
57 defp query_with(q, :rum, search_query) do
58 from([a, o] in q,
59 where:
60 fragment(
61 "? @@ plainto_tsquery('english', ?)",
62 o.fts_content,
63 ^search_query
64 ),
65 order_by: [fragment("? <=> now()::date", o.inserted_at)]
66 )
67 end
68
69 defp maybe_restrict_local(q, user) do
70 limit = Pleroma.Config.get([:instance, :limit_to_local_content], :unauthenticated)
71
72 case {limit, user} do
73 {:all, _} -> restrict_local(q)
74 {:unauthenticated, %User{}} -> q
75 {:unauthenticated, _} -> restrict_local(q)
76 {false, _} -> q
77 end
78 end
79
80 defp restrict_local(q), do: where(q, local: true)
81
82 defp maybe_fetch(activities, user, search_query) do
83 with true <- Regex.match?(~r/https?:/, search_query),
84 {:ok, object} <- Fetcher.fetch_object_from_id(search_query),
85 %Activity{} = activity <- Activity.get_create_by_object_ap_id(object.data["id"]),
86 true <- Visibility.visible_for_user?(activity, user) do
87 activities ++ [activity]
88 else
89 _ -> activities
90 end
91 end
92 end