postland/lib/postland/activities.ex
2024-10-11 02:44:55 +00:00

64 lines
1.5 KiB
Elixir

defmodule Postland.Activities do
use Phoenix.VerifiedRoutes, endpoint: PostlandWeb.Endpoint, router: PostlandWeb.Router
require Logger
alias Postland.Activity
alias Postland.Repo
alias Postland.Follows
def process_activity(params) do
case record_activity(params) do
{:ok, activity} ->
cause_effects(activity)
other ->
other
end
end
def record_activity(params) do
params
|> Activity.changeset()
|> Repo.insert()
end
def cause_effects(%Activity{type: "Accept", data: %{"object" => %{"type" => "Follow", "id" => follow_id}}} = activity) do
pattern = ~r|/follows/([^/]+)|
actor_id = case Regex.run(pattern, follow_id) do
[_, encoded_actor_id] ->
Base.url_decode64!(encoded_actor_id, padding: false)
_other ->
nil
end
case Follows.get(Postland.my_actor_id(), actor_id) do
nil ->
Logger.warning("Got accept for a follow we don't have in the db: #{actor_id}")
{:ok, activity}
request ->
Follows.confirm_request(request)
end
{:ok, activity}
end
def cause_effects(%Activity{actor_id: actor_id, type: "Follow", data: %{"object" => object}} = activity) do
if object == Postland.my_actor_id() do
case Postland.Follows.record_inbound_request(actor_id) do
{:ok, _follow} ->
{:ok, activity}
other ->
other
end
else
{:ok, activity}
end
end
def cause_effects(activity), do: {:ok, activity}
end