Apply all suggested changes from reviewers.
[akkoma] / lib / pleroma / web / static_fe / activity_representer.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.StaticFE.ActivityRepresenter do
6 alias Pleroma.Activity
7 alias Pleroma.Object
8 alias Pleroma.User
9 alias Pleroma.Web.ActivityPub.Visibility
10 alias Pleroma.Web.Router.Helpers
11
12 def prepare_activity(%User{} = user, %Activity{} = activity) do
13 object = Object.normalize(activity.data["object"])
14
15 %{}
16 |> set_user(user)
17 |> set_object(object)
18 |> set_title(object)
19 |> set_content(object)
20 |> set_link(activity.id)
21 |> set_published(object)
22 |> set_sensitive(object)
23 |> set_attachment(object.data["attachment"])
24 |> set_attachments(object)
25 end
26
27 defp set_user(data, %User{} = user), do: Map.put(data, :user, user)
28
29 defp set_object(data, %Object{} = object), do: Map.put(data, :object, object)
30
31 defp set_title(data, %Object{data: %{"name" => name}}) when is_binary(name),
32 do: Map.put(data, :title, name)
33
34 defp set_title(data, %Object{data: %{"summary" => summary}}) when is_binary(summary),
35 do: Map.put(data, :title, summary)
36
37 defp set_title(data, _), do: Map.put(data, :title, nil)
38
39 defp set_content(data, %Object{data: %{"content" => content}}) when is_binary(content),
40 do: Map.put(data, :content, content)
41
42 defp set_content(data, _), do: Map.put(data, :content, nil)
43
44 defp set_attachment(data, attachment), do: Map.put(data, :attachment, attachment)
45
46 defp set_link(data, activity_id),
47 do: Map.put(data, :link, Helpers.o_status_url(Pleroma.Web.Endpoint, :notice, activity_id))
48
49 defp set_published(data, %Object{data: %{"published" => published}}),
50 do: Map.put(data, :published, published)
51
52 defp set_sensitive(data, %Object{data: %{"sensitive" => sensitive}}),
53 do: Map.put(data, :sensitive, sensitive)
54
55 # TODO: attachments
56 defp set_attachments(data, _), do: Map.put(data, :attachments, [])
57
58 def represent(activity_id) do
59 with %Activity{data: %{"type" => "Create"}} = activity <-
60 Activity.get_by_id_with_object(activity_id),
61 true <- Visibility.is_public?(activity),
62 {:ok, %User{} = user} <- User.get_or_fetch(activity.data["actor"]) do
63 {:ok, prepare_activity(user, activity)}
64 else
65 {:error, reason} -> {:error, reason}
66 _error -> {:error, "Not found"}
67 end
68 end
69 end