Add notice compatibility routes for other frontends
[akkoma] / lib / pleroma / web / activity_pub / object_validators / attachment_validator.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.ActivityPub.ObjectValidators.AttachmentValidator do
6 use Ecto.Schema
7
8 alias Pleroma.EctoType.ActivityPub.ObjectValidators
9 alias Pleroma.Web.ActivityPub.ObjectValidators.UrlObjectValidator
10
11 import Ecto.Changeset
12
13 @primary_key false
14 embedded_schema do
15 field(:type, :string)
16 field(:mediaType, :string, default: "application/octet-stream")
17 field(:name, :string)
18 field(:blurhash, :string)
19
20 embeds_many :url, UrlObjectValidator, primary_key: false do
21 field(:type, :string)
22 field(:href, ObjectValidators.Uri)
23 field(:mediaType, :string, default: "application/octet-stream")
24 end
25 end
26
27 def cast_and_validate(data) do
28 data
29 |> cast_data()
30 |> validate_data()
31 end
32
33 def cast_data(data) do
34 %__MODULE__{}
35 |> changeset(data)
36 end
37
38 def changeset(struct, data) do
39 data =
40 data
41 |> fix_media_type()
42 |> fix_url()
43
44 struct
45 |> cast(data, [:type, :mediaType, :name, :blurhash])
46 |> cast_embed(:url, with: &url_changeset/2)
47 |> validate_inclusion(:type, ~w[Link Document Audio Image Video])
48 |> validate_required([:type, :mediaType, :url])
49 end
50
51 def url_changeset(struct, data) do
52 data = fix_media_type(data)
53
54 struct
55 |> cast(data, [:type, :href, :mediaType])
56 |> validate_inclusion(:type, ["Link"])
57 |> validate_required([:type, :href, :mediaType])
58 end
59
60 def fix_media_type(data) do
61 data = Map.put_new(data, "mediaType", data["mimeType"])
62
63 if MIME.valid?(data["mediaType"]) do
64 data
65 else
66 Map.put(data, "mediaType", "application/octet-stream")
67 end
68 end
69
70 defp handle_href(href, mediaType) do
71 [
72 %{
73 "href" => href,
74 "type" => "Link",
75 "mediaType" => mediaType
76 }
77 ]
78 end
79
80 defp fix_url(data) do
81 cond do
82 is_binary(data["url"]) ->
83 Map.put(data, "url", handle_href(data["url"], data["mediaType"]))
84
85 is_binary(data["href"]) and data["url"] == nil ->
86 Map.put(data, "url", handle_href(data["href"], data["mediaType"]))
87
88 true ->
89 data
90 end
91 end
92
93 def validate_data(cng) do
94 cng
95 |> validate_inclusion(:type, ~w[Document Audio Image Video])
96 |> validate_required([:mediaType, :url, :type])
97 end
98 end