1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.ActivityPub.ObjectValidators.AttachmentValidator do
8 alias Pleroma.EctoType.ActivityPub.ObjectValidators
16 field(:mediaType, ObjectValidators.MIME, default: "application/octet-stream")
18 field(:blurhash, :string)
20 embeds_many :url, UrlObjectValidator, primary_key: false do
22 field(:href, ObjectValidators.Uri)
23 field(:mediaType, ObjectValidators.MIME, default: "application/octet-stream")
24 field(:width, :integer)
25 field(:height, :integer)
29 def cast_and_validate(data) do
35 def cast_data(data) do
40 def changeset(struct, data) do
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])
53 def url_changeset(struct, data) do
54 data = fix_media_type(data)
57 |> cast(data, [:type, :href, :mediaType, :width, :height])
58 |> validate_inclusion(:type, ["Link"])
59 |> validate_required([:type, :href, :mediaType])
62 def fix_media_type(data) do
63 Map.put_new(data, "mediaType", data["mimeType"] || "application/octet-stream")
66 defp handle_href(href, mediaType, data) do
71 "mediaType" => mediaType,
72 "width" => data["width"],
73 "height" => data["height"]
80 is_binary(data["url"]) ->
81 Map.put(data, "url", handle_href(data["url"], data["mediaType"], data))
83 is_binary(data["href"]) and data["url"] == nil ->
84 Map.put(data, "url", handle_href(data["href"], data["mediaType"], data))
91 defp validate_data(cng) do
93 |> validate_inclusion(:type, ~w[Document Audio Image Video])
94 |> validate_required([:mediaType, :type])