1 defmodule Pleroma.Search.Meilisearch do
3 require Pleroma.Constants
7 import Pleroma.Activity.Search
10 defp meili_headers() do
11 private_key = Pleroma.Config.get([Pleroma.Search.Meilisearch, :private_key])
13 if is_nil(private_key), do: [], else: [{"X-Meili-API-Key", private_key}]
16 def meili_get!(path) do
17 endpoint = Pleroma.Config.get([Pleroma.Search.Meilisearch, :url])
21 Path.join(endpoint, path),
25 Jason.decode!(result.body)
28 def meili_post!(path, params) do
29 endpoint = Pleroma.Config.get([Pleroma.Search.Meilisearch, :url])
33 Path.join(endpoint, path),
34 Jason.encode!(params),
38 Jason.decode!(result.body)
41 def meili_delete!(path) do
42 endpoint = Pleroma.Config.get([Pleroma.Search.Meilisearch, :url])
47 Path.join(endpoint, path),
54 def search(user, query, options \\ []) do
55 limit = Enum.min([Keyword.get(options, :limit), 40])
56 offset = Keyword.get(options, :offset, 0)
57 author = Keyword.get(options, :author)
61 "/indexes/objects/search",
62 %{q: query, offset: offset, limit: limit}
65 hits = result["hits"] |> Enum.map(& &1["ap"])
69 |> Activity.create_by_object_ap_id()
70 |> Activity.with_preloaded_object()
71 |> Activity.with_preloaded_object()
72 |> Activity.restrict_deactivated_users()
73 |> maybe_restrict_local(user)
74 |> maybe_restrict_author(author)
75 |> maybe_restrict_blocked(user)
76 |> maybe_fetch(user, query)
77 |> order_by([object: obj], desc: obj.data["published"])
80 _ -> maybe_fetch([], user, query)
84 def object_to_search_data(object) do
85 if not is_nil(object) and object.data["type"] == "Note" and
86 Pleroma.Constants.as_public() in object.data["to"] do
90 case data["content"] do
91 [nil | rest] -> to_string(rest)
96 with {:ok, scrubbed} <- FastSanitize.strip_tags(content_str),
97 trimmed <- String.trim(scrubbed) do
101 if String.length(content) > 1 do
102 {:ok, published, _} = DateTime.from_iso8601(data["published"])
108 published: published |> DateTime.to_unix()
114 def add_to_index(activity) do
115 maybe_search_data = object_to_search_data(activity.object)
117 if activity.data["type"] == "Create" and maybe_search_data do
120 "/indexes/objects/documents",
124 if not Map.has_key?(result, "updateId") do
125 Logger.error("Failed to add activity #{activity.id} to index: #{inspect(result)}")
130 def remove_from_index(object) do
131 meili_delete!("/indexes/objects/documents/#{object.id}")