dbe6b2d672ceb8e596dba5adeec552973b49a16a
[akkoma] / lib / pleroma / search / meilisearch.ex
1 defmodule Pleroma.Search.Meilisearch do
2 require Logger
3 require Pleroma.Constants
4
5 alias Pleroma.Activity
6
7 import Pleroma.Activity.Search
8 import Ecto.Query
9
10 def search(user, query, options \\ []) do
11 limit = Enum.min([Keyword.get(options, :limit), 40])
12 offset = Keyword.get(options, :offset, 0)
13 author = Keyword.get(options, :author)
14
15 endpoint = Pleroma.Config.get([Pleroma.Search.Meilisearch, :url])
16
17 {:ok, result} =
18 Pleroma.HTTP.post(
19 "#{endpoint}/indexes/objects/search",
20 Jason.encode!(%{q: query, offset: offset, limit: limit})
21 )
22
23 hits = Jason.decode!(result.body)["hits"] |> Enum.map(& &1["ap"])
24
25 try do
26 hits
27 |> Activity.create_by_object_ap_id()
28 |> Activity.with_preloaded_object()
29 |> Activity.with_preloaded_object()
30 |> Activity.restrict_deactivated_users()
31 |> maybe_restrict_local(user)
32 |> maybe_restrict_author(author)
33 |> maybe_restrict_blocked(user)
34 |> maybe_fetch(user, query)
35 |> order_by([activity], desc: activity.id)
36 |> Pleroma.Repo.all()
37 rescue
38 _ -> maybe_fetch([], user, query)
39 end
40 end
41
42 def add_to_index(activity) do
43 object = activity.object
44
45 if activity.data["type"] == "Create" and not is_nil(object) and object.data["type"] == "Note" and
46 Pleroma.Constants.as_public() in object.data["to"] do
47 data = object.data
48
49 endpoint = Pleroma.Config.get([Pleroma.Search.Meilisearch, :url])
50
51 {:ok, result} =
52 Pleroma.HTTP.post(
53 "#{endpoint}/indexes/objects/documents",
54 Jason.encode!([%{id: object.id, source: data["source"], ap: data["id"]}])
55 )
56
57 if not Map.has_key?(Jason.decode!(result.body), "updateId") do
58 Logger.error("Failed to add activity #{activity.id} to index: #{result.body}")
59 end
60 end
61 end
62
63 def remove_from_index(object) do
64 endpoint = Pleroma.Config.get([Pleroma.Search.Meilisearch, :url])
65
66 {:ok, _} =
67 Pleroma.HTTP.request(
68 :delete,
69 "#{endpoint}/indexes/objects/documents/#{object.id}",
70 "",
71 [],
72 []
73 )
74 end
75 end