chore: Add functions for recursively fetching reply threads

This commit is contained in:
Ro 2025-01-27 19:06:58 -06:00
parent ec6b728611
commit a7f2ab0659
Signed by: ro
GPG key ID: 5B5AD5A568CDABF9

59
lib/postland/replies.ex Normal file
View file

@ -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