Add collection fetching module
[akkoma] / lib / pleroma / collections / fetcher.ex
1 # Akkoma: The cooler fediverse server
2 # Copyright © 2022- Akkoma Authors <https://akkoma.dev/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Akkoma.Collections.Fetcher do
6 @moduledoc """
7 Activitypub Collections fetching functions
8 see: https://www.w3.org/TR/activitystreams-core/#paging
9 """
10 alias Pleroma.Object.Fetcher
11 alias Pleroma.Config
12
13 def fetch_collection_by_ap_id(ap_id) when is_binary(ap_id) do
14 fetch_collection(ap_id)
15 end
16
17 defp fetch_collection(ap_id) do
18 with {:ok, page} <- Fetcher.fetch_and_contain_remote_object_from_id(ap_id) do
19 {:ok, objects_from_collection(page)}
20 end
21 end
22
23 defp items_in_page(%{"type" => type, "orderedItems" => items})
24 when is_list(items) and type in ["OrderedCollection", "OrderedCollectionPage"],
25 do: items
26
27 defp items_in_page(%{"type" => type, "items" => items})
28 when is_list(items) and type in ["Collection", "CollectionPage"],
29 do: items
30
31 defp objects_from_collection(%{"type" => "OrderedCollection", "orderedItems" => items})
32 when is_list(items),
33 do: items
34
35 defp objects_from_collection(%{"type" => "Collection", "items" => items}) when is_list(items),
36 do: items
37
38 defp objects_from_collection(%{"type" => type, "first" => first})
39 when is_binary(first) and type in ["Collection", "OrderedCollection"] do
40 fetch_page_items(first)
41 end
42
43 defp objects_from_collection(%{"type" => type, "first" => %{"id" => id}})
44 when is_binary(id) and type in ["Collection", "OrderedCollection"] do
45 fetch_page_items(id)
46 end
47
48 defp fetch_page_items(id, items \\ []) do
49 if Enum.count(items) >= Config.get([:activitypub, :max_collection_objects]) do
50 items
51 else
52 {:ok, page} = Fetcher.fetch_and_contain_remote_object_from_id(id)
53 objects = items_in_page(page)
54
55 if Enum.count(objects) > 0 do
56 maybe_next_page(page, items ++ objects)
57 else
58 items
59 end
60 end
61 end
62
63 defp maybe_next_page(%{"next" => id}, items) when is_binary(id) do
64 fetch_page_items(id, items)
65 end
66
67 defp maybe_next_page(_, items), do: items
68 end