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', ?)",
47 defp query_with(q, :rum, search_query) do
51 "? @@ plainto_tsquery('english', ?)",
55 order_by: [fragment("? <=> now()::date", o.inserted_at)]
59 # users can search everything
60 defp maybe_restrict_local(q, %User{}), do: q
62 # unauthenticated users can only search local activities
63 defp maybe_restrict_local(q, _), do: where(q, local: true)
65 defp maybe_fetch(activities, user, search_query) do
66 with true <- Regex.match?(~r/https?:/, search_query),
67 {:ok, object} <- Fetcher.fetch_object_from_id(search_query),
68 %Activity{} = activity <- Activity.get_create_by_object_ap_id(object.data["id"]),
69 true <- Visibility.visible_for_user?(activity, user) do
70 activities ++ [activity]