postland/lib/activity_pub.ex

71 lines
1.6 KiB
Elixir
Raw Permalink Normal View History

2024-10-09 22:45:28 +00:00
defmodule ActivityPub do
2024-10-24 00:10:48 +00:00
alias ActivityPub.Headers
2024-10-14 01:02:59 +00:00
def get(url, actor_url, private_key) do
2024-10-24 00:10:48 +00:00
headers = Headers.signing_headers("GET", url, "", actor_url, private_key)
2024-10-14 01:02:59 +00:00
Req.new(url: url)
|> Req.Request.put_header("accept", "application/activity+json")
|> Req.Request.put_headers(headers)
|> Req.get()
|> case do
{:ok, response} ->
{:ok, response.body}
other ->
other
end
end
2024-10-24 00:10:48 +00:00
def post_activity(sender_id, private_key, inbox, activity) do
2024-12-27 03:03:37 +00:00
if String.contains?(inbox, "example.com") do
{:ok, %{status: 200, body: "ok"}}
else
body = Jason.encode!(activity)
headers =
Headers.signing_headers(
"POST",
inbox,
body,
sender_id,
private_key
)
Req.post(inbox, headers: headers, body: body)
end
2024-10-24 00:10:48 +00:00
end
2024-10-10 00:01:44 +00:00
def fetch_actor(actor_id) do
2024-12-27 03:03:37 +00:00
if String.contains?(actor_id, "example.com") do
{:ok,
%{
"@context" => [
"https://www.w3.org/ns/activitystreams",
"https://w3id.org/security/v1"
],
"id" => actor_id,
"type" => "Person",
"preferredUsername" => "example",
"name" => "Example User",
"inbox" => "#{actor_id}/inbox"
}}
else
request =
Req.new(url: actor_id)
|> Req.Request.put_header("accept", "application/json")
2024-10-10 00:01:44 +00:00
2024-12-27 03:03:37 +00:00
case Req.get(request) do
{:ok, %{status: 200} = result} ->
{:ok, result.body}
2024-10-10 00:01:44 +00:00
2024-12-27 03:03:37 +00:00
{:ok, %{status: 404}} ->
nil
2024-11-27 00:04:08 +00:00
2024-12-27 03:03:37 +00:00
error ->
error
end
2024-10-14 01:02:59 +00:00
end
2024-10-10 00:01:44 +00:00
end
2024-10-09 22:45:28 +00:00
end