Merge pull request 'Add PWA config' (#329) from pwa into develop
[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
10 import Ecto.Changeset
11
12 @primary_key false
13 embedded_schema do
14 field(:id, :string)
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 field(:width, :integer)
25 field(:height, :integer)
26 end
27 end
28
29 def cast_and_validate(data) do
30 data
31 |> cast_data()
32 |> validate_data()
33 end
34
35 def cast_data(data) do
36 %__MODULE__{}
37 |> changeset(data)
38 end
39
40 def changeset(struct, data) do
41 data =
42 data
43 |> fix_media_type()
44 |> fix_url()
45
46 struct
47 |> cast(data, [:id, :type, :mediaType, :name, :blurhash])
48 |> cast_embed(:url, with: &url_changeset/2, required: true)
49 |> validate_inclusion(:type, ~w[Link Document Audio Image Video])
50 |> validate_required([:type, :mediaType])
51 end
52
53 def url_changeset(struct, data) do
54 data = fix_media_type(data)
55
56 struct
57 |> cast(data, [:type, :href, :mediaType, :width, :height])
58 |> validate_inclusion(:type, ["Link"])
59 |> validate_required([:type, :href, :mediaType])
60 end
61
62 def fix_media_type(data) do
63 data = Map.put_new(data, "mediaType", data["mimeType"])
64
65 if is_bitstring(data["mediaType"]) && MIME.extensions(data["mediaType"]) != [] do
66 data
67 else
68 Map.put(data, "mediaType", "application/octet-stream")
69 end
70 end
71
72 defp handle_href(href, mediaType, data) do
73 [
74 %{
75 "href" => href,
76 "type" => "Link",
77 "mediaType" => mediaType,
78 "width" => data["width"],
79 "height" => data["height"]
80 }
81 ]
82 end
83
84 defp fix_url(data) do
85 cond do
86 is_binary(data["url"]) ->
87 Map.put(data, "url", handle_href(data["url"], data["mediaType"], data))
88
89 is_binary(data["href"]) and data["url"] == nil ->
90 Map.put(data, "url", handle_href(data["href"], data["mediaType"], data))
91
92 true ->
93 data
94 end
95 end
96
97 defp validate_data(cng) do
98 cng
99 |> validate_inclusion(:type, ~w[Document Audio Image Video])
100 |> validate_required([:mediaType, :type])
101 end
102 end