Do some transmogrifying for the output.
[akkoma] / lib / pleroma / web / activity_pub / transmogrifier.ex
1 defmodule Pleroma.Web.ActivityPub.Transmogrifier do
2 @moduledoc """
3 A module to handle coding from internal to wire ActivityPub and back.
4 """
5 alias Pleroma.User
6 alias Pleroma.Web.ActivityPub.ActivityPub
7
8 @doc """
9 Modifies an incoming AP object (mastodon format) to our internal format.
10 """
11 def fix_object(object) do
12 object
13 |> Map.put("actor", object["attributedTo"])
14 end
15
16 # TODO: validate those with a Ecto scheme
17 # - tags
18 # - emoji
19 def handle_incoming(%{"type" => "Create", "object" => %{"type" => "Note"} = object} = data) do
20 with %User{} = user <- User.get_or_fetch_by_ap_id(data["actor"]) do
21 object = fix_object(data["object"])
22 params = %{
23 to: data["to"],
24 object: object,
25 actor: user,
26 context: data["object"]["conversation"],
27 local: false,
28 published: data["published"],
29 additional: Map.take(data, [
30 "cc",
31 "id"
32 ])
33 }
34
35 ActivityPub.create(params)
36 else
37 _e -> :error
38 end
39 end
40
41 @doc
42 """
43 internal -> Mastodon
44 """
45 def prepare_outgoing(%{"type" => "Create", "object" => %{"type" => "Note"} = object} = data) do
46 object = object
47 |> add_mention_tags
48 |> add_attributed_to
49
50 data = data
51 |> Map.put("object", object)
52 |> Map.put("@context", "https://www.w3.org/ns/activitystreams")
53
54 {:ok, data}
55 end
56
57 def add_mention_tags(object) do
58 mentions = object["to"]
59 |> Enum.map(fn (ap_id) -> User.get_cached_by_ap_id(ap_id) end)
60 |> Enum.filter(&(&1))
61 |> Enum.map(fn(user) -> %{"type" => "mention", "href" => user.ap_id, "name" => "@#{user.nickname}"} end)
62
63 tags = object["tags"] || []
64
65 object
66 |> Map.put("tags", tags ++ mentions)
67 end
68
69 def add_attributed_to(object) do
70 attributedTo = object["attributedTo"] || object["actor"]
71
72 object
73 |> Map.put("attributedTo", attributedTo)
74 end
75 end