From a7f2ab0659ab59f58cf0a2859a799da14b30f84a Mon Sep 17 00:00:00 2001 From: Ro Date: Mon, 27 Jan 2025 19:06:58 -0600 Subject: [PATCH] chore: Add functions for recursively fetching reply threads --- lib/postland/replies.ex | 59 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 lib/postland/replies.ex diff --git a/lib/postland/replies.ex b/lib/postland/replies.ex new file mode 100644 index 0000000..79e01a0 --- /dev/null +++ b/lib/postland/replies.ex @@ -0,0 +1,59 @@ +defmodule Postland.Replies do + def recurse_note(url, actor_id, private_key) when is_binary(url) do + {:ok, note} = ActivityPub.get(url, actor_id, private_key) + dbg(note) + + reply_collection = + fetch_whole_collection(note["replies"], actor_id, private_key) + + {note, reply_collection} + end + + def recurse_note(map, _actor_id, _private_key) when is_map(map), do: map + + def fetch_whole_collection(%{"first" => first}, actor_id, private_key) do + fetch_whole_collection(first, actor_id, private_key) + end + + def fetch_whole_collection(map, actor_id, private_key) when is_map(map) do + next_url = + dbg(map) + + items = + case Map.get(map, "items") do + [] -> + [] + + list when is_list(list) -> + Enum.map(list, &recurse_note(&1, actor_id, private_key)) + end + + next = + case Map.get(map, "next") do + nil -> + [] + + next_url -> + fetch_whole_collection(next_url, actor_id, private_key) + end + + items ++ next + end + + def fetch_whole_collection(url, actor_id, private_key) when is_binary(url) do + url + |> ActivityPub.get(actor_id, private_key) + |> case do + {:ok, collection_page} -> + fetch_whole_collection(collection_page, actor_id, private_key) + + other -> + other + end + end + + def _debug({note, replies}, level \\ 0) do + IO.puts("#{String.pad_leading("", level * 2)}#{Map.get(note, "content")}") + Enum.each(replies, &_debug(&1, level + 1)) + end +end