1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 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
9 alias Pleroma.Web.ActivityPub.ObjectValidators.UrlObjectValidator
16 field(:mediaType, :string, 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, :string, default: "application/octet-stream")
27 def cast_and_validate(data) do
33 def cast_data(data) do
38 def changeset(struct, data) do
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])
51 def url_changeset(struct, data) do
52 data = fix_media_type(data)
55 |> cast(data, [:type, :href, :mediaType])
56 |> validate_inclusion(:type, ["Link"])
57 |> validate_required([:type, :href, :mediaType])
60 def fix_media_type(data) do
61 data = Map.put_new(data, "mediaType", data["mimeType"])
63 if MIME.valid?(data["mediaType"]) do
66 Map.put(data, "mediaType", "application/octet-stream")
70 defp handle_href(href, mediaType) do
75 "mediaType" => mediaType
82 is_binary(data["url"]) ->
83 Map.put(data, "url", handle_href(data["url"], data["mediaType"]))
85 is_binary(data["href"]) and data["url"] == nil ->
86 Map.put(data, "url", handle_href(data["href"], data["mediaType"]))
93 def validate_data(cng) do
95 |> validate_inclusion(:type, ~w[Document Audio Image Video])
96 |> validate_required([:mediaType, :url, :type])