logo

pleroma

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

attachment_validator.ex (2469B)


  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)
  12. field(:mediaType, ObjectValidators.MIME, default: "application/octet-stream")
  13. field(:name, :string)
  14. field(:blurhash, :string)
  15. embeds_many :url, UrlObjectValidator, primary_key: false do
  16. field(:type, :string)
  17. field(:href, ObjectValidators.Uri)
  18. field(:mediaType, ObjectValidators.MIME, default: "application/octet-stream")
  19. field(:width, :integer)
  20. field(:height, :integer)
  21. end
  22. end
  23. def cast_and_validate(data) do
  24. data
  25. |> cast_data()
  26. |> validate_data()
  27. end
  28. def cast_data(data) do
  29. %__MODULE__{}
  30. |> changeset(data)
  31. end
  32. def changeset(struct, data) do
  33. data =
  34. data
  35. |> fix_media_type()
  36. |> fix_url()
  37. struct
  38. |> cast(data, [:id, :type, :mediaType, :name, :blurhash])
  39. |> cast_embed(:url, with: &url_changeset/2, required: true)
  40. |> validate_inclusion(:type, ~w[Link Document Audio Image Video])
  41. |> validate_required([:type, :mediaType])
  42. end
  43. def url_changeset(struct, data) do
  44. data = fix_media_type(data)
  45. struct
  46. |> cast(data, [:type, :href, :mediaType, :width, :height])
  47. |> validate_inclusion(:type, ["Link"])
  48. |> validate_required([:type, :href, :mediaType])
  49. end
  50. def fix_media_type(data) do
  51. Map.put_new(data, "mediaType", data["mimeType"] || "application/octet-stream")
  52. end
  53. defp handle_href(href, mediaType, data) do
  54. [
  55. %{
  56. "href" => href,
  57. "type" => "Link",
  58. "mediaType" => mediaType,
  59. "width" => data["width"],
  60. "height" => data["height"]
  61. }
  62. ]
  63. end
  64. defp fix_url(data) do
  65. cond do
  66. is_binary(data["url"]) ->
  67. Map.put(data, "url", handle_href(data["url"], data["mediaType"], data))
  68. is_binary(data["href"]) and data["url"] == nil ->
  69. Map.put(data, "url", handle_href(data["href"], data["mediaType"], data))
  70. true ->
  71. data
  72. end
  73. end
  74. defp validate_data(cng) do
  75. cng
  76. |> validate_inclusion(:type, ~w[Document Audio Image Video])
  77. |> validate_required([:mediaType, :type])
  78. end
  79. end