f4af3aed35b82570d30b39e813d47ded09892dd7
[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 def handle_incoming(%{"type" => "Follow", "object" => followed, "actor" => follower, "id" => id}) do
42 with %User{} = followed <- User.get_cached_by_ap_id(followed),
43 %User{} = follower <- User.get_or_fetch_by_ap_id(follower),
44 {:ok, activity} <- ActivityPub.follow(follower, followed, id, false) do
45 # TODO: Send an "Accept" activity.
46 User.follow(follower, followed)
47 {:ok, activity}
48 else
49 _e -> :error
50 end
51 end
52
53 def handle_incoming(_), do: :error
54
55 @doc
56 """
57 internal -> Mastodon
58 """
59 def prepare_outgoing(%{"type" => "Create", "object" => %{"type" => "Note"} = object} = data) do
60 object = object
61 |> add_mention_tags
62 |> add_attributed_to
63
64 data = data
65 |> Map.put("object", object)
66 |> Map.put("@context", "https://www.w3.org/ns/activitystreams")
67
68 {:ok, data}
69 end
70
71 def add_mention_tags(object) do
72 mentions = object["to"]
73 |> Enum.map(fn (ap_id) -> User.get_cached_by_ap_id(ap_id) end)
74 |> Enum.filter(&(&1))
75 |> Enum.map(fn(user) -> %{"type" => "Mention", "href" => user.ap_id, "name" => "@#{user.nickname}"} end)
76
77 tags = object["tag"] || []
78
79 object
80 |> Map.put("tag", tags ++ mentions)
81 end
82
83 def add_attributed_to(object) do
84 attributedTo = object["attributedTo"] || object["actor"]
85
86 object
87 |> Map.put("attributedTo", attributedTo)
88 end
89 end