Merge pull request '[#37] fix frienderica pinned collection fetching' (#42) from...
[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 def fetch_collection(ap_id) when is_binary(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 else
21 e ->
22 Logger.error("Could not fetch collection #{ap_id} - #{inspect(e)}")
23 e
24 end
25 end
26
27 def fetch_collection(%{"type" => type} = page)
28 when type in ["Collection", "OrderedCollection"] do
29 {:ok, objects_from_collection(page)}
30 end
31
32 defp items_in_page(%{"type" => type, "orderedItems" => items})
33 when is_list(items) and type in ["OrderedCollection", "OrderedCollectionPage"],
34 do: items
35
36 defp items_in_page(%{"type" => type, "items" => items})
37 when is_list(items) and type in ["Collection", "CollectionPage"],
38 do: items
39
40 defp objects_from_collection(%{"type" => "OrderedCollection", "orderedItems" => items})
41 when is_list(items),
42 do: items
43
44 defp objects_from_collection(%{"type" => "Collection", "items" => items}) when is_list(items),
45 do: items
46
47 defp objects_from_collection(%{"type" => type, "first" => first})
48 when is_binary(first) and type in ["Collection", "OrderedCollection"] do
49 fetch_page_items(first)
50 end
51
52 defp objects_from_collection(%{"type" => type, "first" => %{"id" => id}})
53 when is_binary(id) and type in ["Collection", "OrderedCollection"] do
54 fetch_page_items(id)
55 end
56
57 defp fetch_page_items(id, items \\ []) do
58 if Enum.count(items) >= Config.get([:activitypub, :max_collection_objects]) do
59 items
60 else
61 {:ok, page} = Fetcher.fetch_and_contain_remote_object_from_id(id)
62 objects = items_in_page(page)
63
64 if Enum.count(objects) > 0 do
65 maybe_next_page(page, items ++ objects)
66 else
67 items
68 end
69 end
70 end
71
72 defp maybe_next_page(%{"next" => id}, items) when is_binary(id) do
73 fetch_page_items(id, items)
74 end
75
76 defp maybe_next_page(_, items), do: items
77 end