1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Activity.Search do
7 alias Pleroma.Object.Fetcher
10 alias Pleroma.Web.ActivityPub.Visibility
14 def search(user, search_query) do
15 index_type = if Pleroma.Config.get([:database, :rum_enabled]), do: :rum, else: :gin
18 |> Activity.with_preloaded_object()
19 |> Activity.restrict_deactivated_users()
21 |> query_with(index_type, search_query)
22 |> maybe_restrict_local(user)
24 |> maybe_fetch(user, search_query)
27 defp restrict_public(q) do
29 where: fragment("?->>'type' = 'Create'", a.data),
30 where: "https://www.w3.org/ns/activitystreams#Public" in a.recipients,
35 defp query_with(q, :gin, search_query) do
39 "to_tsvector('english', ?->>'content') @@ plainto_tsquery('english', ?)",
46 defp query_with(q, :rum, search_query) do
50 "? @@ plainto_tsquery('english', ?)",
54 order_by: [fragment("? <=> now()::date", o.inserted_at)]
58 defp maybe_restrict_local(q, user) do
59 limit = Pleroma.Config.get([:instance, :limit_to_local_content], :unauthenticated)
62 {:all, _} -> restrict_local(q)
63 {:unauthenticated, %User{}} -> q
64 {:unauthenticated, _} -> restrict_local(q)
69 defp restrict_local(q), do: where(q, local: true)
71 defp maybe_fetch(activities, user, search_query) do
72 with true <- Regex.match?(~r/https?:/, search_query),
73 {:ok, object} <- Fetcher.fetch_object_from_id(search_query),
74 %Activity{} = activity <- Activity.get_create_by_object_ap_id(object.data["id"]),
75 true <- Visibility.visible_for_user?(activity, user) do
76 activities ++ [activity]