logo

pleroma

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

upload.ex (9334B)


  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.Upload do
  5. @moduledoc """
  6. Manage user uploads
  7. Options:
  8. * `:type`: presets for activity type (defaults to Document) and size limits from app configuration
  9. * `:description`: upload alternative text
  10. * `:base_url`: override base url
  11. * `:uploader`: override uploader
  12. * `:filters`: override filters
  13. * `:size_limit`: override size limit
  14. * `:activity_type`: override activity type
  15. The `%Pleroma.Upload{}` struct: all documented fields are meant to be overwritten in filters:
  16. * `:id` - the upload id.
  17. * `:name` - the upload file name.
  18. * `:path` - the upload path: set at first to `id/name` but can be changed. Keep in mind that the path
  19. is once created permanent and changing it (especially in uploaders) is probably a bad idea!
  20. * `:tempfile` - path to the temporary file. Prefer in-place changes on the file rather than changing the
  21. path as the temporary file is also tracked by `Plug.Upload{}` and automatically deleted once the request is over.
  22. * `:width` - width of the media in pixels
  23. * `:height` - height of the media in pixels
  24. * `:blurhash` - string hash of the image encoded with the blurhash algorithm (https://blurha.sh/)
  25. Related behaviors:
  26. * `Pleroma.Uploaders.Uploader`
  27. * `Pleroma.Upload.Filter`
  28. """
  29. alias Ecto.UUID
  30. alias Pleroma.Maps
  31. alias Pleroma.Web.ActivityPub.Utils
  32. require Logger
  33. @type source ::
  34. Plug.Upload.t()
  35. | (data_uri_string :: String.t())
  36. | {:from_local, name :: String.t(), id :: String.t(), path :: String.t()}
  37. | map()
  38. @type option ::
  39. {:type, :avatar | :banner | :background}
  40. | {:description, String.t()}
  41. | {:activity_type, String.t()}
  42. | {:size_limit, nil | non_neg_integer()}
  43. | {:uploader, module()}
  44. | {:filters, [module()]}
  45. | {:actor, String.t()}
  46. @type t :: %__MODULE__{
  47. id: String.t(),
  48. name: String.t(),
  49. tempfile: String.t(),
  50. content_type: String.t(),
  51. width: integer(),
  52. height: integer(),
  53. blurhash: String.t(),
  54. description: String.t(),
  55. path: String.t()
  56. }
  57. defstruct [
  58. :id,
  59. :name,
  60. :tempfile,
  61. :content_type,
  62. :width,
  63. :height,
  64. :blurhash,
  65. :description,
  66. :path
  67. ]
  68. @config_impl Application.compile_env(:pleroma, [__MODULE__, :config_impl], Pleroma.Config)
  69. defp get_description(upload) do
  70. case {upload.description, Pleroma.Config.get([Pleroma.Upload, :default_description])} do
  71. {description, _} when is_binary(description) -> description
  72. {_, :filename} -> upload.name
  73. {_, str} when is_binary(str) -> str
  74. _ -> ""
  75. end
  76. end
  77. @spec store(source, options :: [option()]) :: {:ok, map()} | {:error, any()}
  78. @doc "Store a file. If using a `Plug.Upload{}` as the source, be sure to use `Majic.Plug` to ensure its content_type and filename is correct."
  79. def store(upload, opts \\ []) do
  80. opts = get_opts(opts)
  81. with {:ok, upload} <- prepare_upload(upload, opts),
  82. upload = %__MODULE__{upload | path: upload.path || "#{upload.id}/#{upload.name}"},
  83. {:ok, upload} <- Pleroma.Upload.Filter.filter(opts.filters, upload),
  84. description = get_description(upload),
  85. {_, true} <-
  86. {:description_limit,
  87. String.length(description) <= Pleroma.Config.get([:instance, :description_limit])},
  88. {:ok, url_spec} <- Pleroma.Uploaders.Uploader.put_file(opts.uploader, upload) do
  89. {:ok,
  90. %{
  91. "id" => Utils.generate_object_id(),
  92. "type" => opts.activity_type,
  93. "mediaType" => upload.content_type,
  94. "url" => [
  95. %{
  96. "type" => "Link",
  97. "mediaType" => upload.content_type,
  98. "href" => url_from_spec(upload, opts.base_url, url_spec)
  99. }
  100. |> Maps.put_if_present("width", upload.width)
  101. |> Maps.put_if_present("height", upload.height)
  102. ],
  103. "name" => description
  104. }
  105. |> Maps.put_if_present("blurhash", upload.blurhash)}
  106. else
  107. {:description_limit, _} ->
  108. {:error, :description_too_long}
  109. {:error, error} ->
  110. Logger.error(
  111. "#{__MODULE__} store (using #{inspect(opts.uploader)}) failed: #{inspect(error)}"
  112. )
  113. {:error, error}
  114. end
  115. end
  116. def char_unescaped?(char) do
  117. URI.char_unreserved?(char) or char == ?/
  118. end
  119. defp get_opts(opts) do
  120. {size_limit, activity_type} =
  121. case Keyword.get(opts, :type) do
  122. :banner ->
  123. {Pleroma.Config.get!([:instance, :banner_upload_limit]), "Image"}
  124. :avatar ->
  125. {Pleroma.Config.get!([:instance, :avatar_upload_limit]), "Image"}
  126. :background ->
  127. {Pleroma.Config.get!([:instance, :background_upload_limit]), "Image"}
  128. _ ->
  129. {Pleroma.Config.get!([:instance, :upload_limit]), "Document"}
  130. end
  131. %{
  132. activity_type: Keyword.get(opts, :activity_type, activity_type),
  133. size_limit: Keyword.get(opts, :size_limit, size_limit),
  134. uploader: Keyword.get(opts, :uploader, Pleroma.Config.get([__MODULE__, :uploader])),
  135. filters: Keyword.get(opts, :filters, Pleroma.Config.get([__MODULE__, :filters])),
  136. description: Keyword.get(opts, :description),
  137. base_url: base_url()
  138. }
  139. end
  140. defp prepare_upload(%Plug.Upload{} = file, opts) do
  141. with :ok <- check_file_size(file.path, opts.size_limit) do
  142. {:ok,
  143. %__MODULE__{
  144. id: UUID.generate(),
  145. name: file.filename,
  146. tempfile: file.path,
  147. content_type: file.content_type,
  148. description: opts.description
  149. }}
  150. end
  151. end
  152. defp prepare_upload(%{img: "data:image/" <> image_data}, opts) do
  153. parsed = Regex.named_captures(~r/(?<filetype>jpeg|png|gif);base64,(?<data>.*)/, image_data)
  154. data = Base.decode64!(parsed["data"], ignore: :whitespace)
  155. hash = Base.encode16(:crypto.hash(:sha256, data), case: :upper)
  156. with :ok <- check_binary_size(data, opts.size_limit),
  157. tmp_path <- tempfile_for_image(data),
  158. {:ok, %{mime_type: content_type}} <-
  159. Majic.perform({:bytes, data}, pool: Pleroma.MajicPool),
  160. [ext | _] <- MIME.extensions(content_type) do
  161. {:ok,
  162. %__MODULE__{
  163. id: UUID.generate(),
  164. name: hash <> "." <> ext,
  165. tempfile: tmp_path,
  166. content_type: content_type,
  167. description: opts.description
  168. }}
  169. end
  170. end
  171. # For Mix.Tasks.MigrateLocalUploads
  172. defp prepare_upload(%__MODULE__{tempfile: path} = upload, _opts) do
  173. with {:ok, %{mime_type: content_type}} <- Majic.perform(path, pool: Pleroma.MajicPool) do
  174. {:ok, %__MODULE__{upload | content_type: content_type}}
  175. end
  176. end
  177. defp check_binary_size(binary, size_limit)
  178. when is_integer(size_limit) and size_limit > 0 and byte_size(binary) >= size_limit do
  179. {:error, :file_too_large}
  180. end
  181. defp check_binary_size(_, _), do: :ok
  182. defp check_file_size(path, size_limit) when is_integer(size_limit) and size_limit > 0 do
  183. with {:ok, %{size: size}} <- File.stat(path),
  184. true <- size <= size_limit do
  185. :ok
  186. else
  187. false -> {:error, :file_too_large}
  188. error -> error
  189. end
  190. end
  191. defp check_file_size(_, _), do: :ok
  192. # Creates a tempfile using the Plug.Upload Genserver which cleans them up
  193. # automatically.
  194. defp tempfile_for_image(data) do
  195. {:ok, tmp_path} = Plug.Upload.random_file("profile_pics")
  196. {:ok, tmp_file} = File.open(tmp_path, [:write, :raw, :binary])
  197. IO.binwrite(tmp_file, data)
  198. tmp_path
  199. end
  200. defp url_from_spec(%__MODULE__{name: name}, base_url, {:file, path}) do
  201. path =
  202. URI.encode(path, &char_unescaped?/1) <>
  203. if Pleroma.Config.get([__MODULE__, :link_name], false) do
  204. "?name=#{URI.encode(name, &char_unescaped?/1)}"
  205. else
  206. ""
  207. end
  208. [base_url, path]
  209. |> Path.join()
  210. end
  211. defp url_from_spec(_upload, _base_url, {:url, url}), do: url
  212. def base_url do
  213. uploader = @config_impl.get([Pleroma.Upload, :uploader])
  214. upload_base_url = @config_impl.get([Pleroma.Upload, :base_url])
  215. public_endpoint = @config_impl.get([uploader, :public_endpoint])
  216. case uploader do
  217. Pleroma.Uploaders.Local ->
  218. upload_base_url || Pleroma.Web.Endpoint.url() <> "/media/"
  219. Pleroma.Uploaders.S3 ->
  220. bucket = @config_impl.get([Pleroma.Uploaders.S3, :bucket])
  221. truncated_namespace = @config_impl.get([Pleroma.Uploaders.S3, :truncated_namespace])
  222. namespace = @config_impl.get([Pleroma.Uploaders.S3, :bucket_namespace])
  223. bucket_with_namespace =
  224. cond do
  225. !is_nil(truncated_namespace) ->
  226. truncated_namespace
  227. !is_nil(namespace) ->
  228. namespace <> ":" <> bucket
  229. true ->
  230. bucket
  231. end
  232. if public_endpoint do
  233. Path.join([public_endpoint, bucket_with_namespace])
  234. else
  235. Path.join([upload_base_url, bucket_with_namespace])
  236. end
  237. _ ->
  238. public_endpoint || upload_base_url || Pleroma.Web.Endpoint.url() <> "/media/"
  239. end
  240. end
  241. end