logo

pleroma

My custom branche(s) on git.pleroma.social/pleroma/pleroma git clone https://anongit.hacktivis.me/git/pleroma.git/

attachment_validator.ex (2542B)


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