Fork of Pleroma with site-specific changes and feature branches https://git.pleroma.social/pleroma/pleroma
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

268 lines
8.7KB

  1. # Pleroma: A lightweight social networking server
  2. # Copyright © 2017-2021 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.Config
  31. alias Pleroma.Maps
  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. @type t :: %__MODULE__{
  46. id: String.t(),
  47. name: String.t(),
  48. tempfile: String.t(),
  49. content_type: String.t(),
  50. width: integer(),
  51. height: integer(),
  52. blurhash: String.t(),
  53. path: String.t()
  54. }
  55. defstruct [:id, :name, :tempfile, :content_type, :width, :height, :blurhash, :path]
  56. defp get_description(opts, upload) do
  57. case {opts[:description], Pleroma.Config.get([Pleroma.Upload, :default_description])} do
  58. {description, _} when is_binary(description) -> description
  59. {_, :filename} -> upload.name
  60. {_, str} when is_binary(str) -> str
  61. _ -> ""
  62. end
  63. end
  64. @spec store(source, options :: [option()]) :: {:ok, Map.t()} | {:error, any()}
  65. @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."
  66. def store(upload, opts \\ []) do
  67. opts = get_opts(opts)
  68. with {:ok, upload} <- prepare_upload(upload, opts),
  69. upload = %__MODULE__{upload | path: upload.path || "#{upload.id}/#{upload.name}"},
  70. {:ok, upload} <- Pleroma.Upload.Filter.filter(opts.filters, upload),
  71. description = get_description(opts, upload),
  72. {_, true} <-
  73. {:description_limit,
  74. String.length(description) <= Pleroma.Config.get([:instance, :description_limit])},
  75. {:ok, url_spec} <- Pleroma.Uploaders.Uploader.put_file(opts.uploader, upload) do
  76. {:ok,
  77. %{
  78. "type" => opts.activity_type,
  79. "mediaType" => upload.content_type,
  80. "url" => [
  81. %{
  82. "type" => "Link",
  83. "mediaType" => upload.content_type,
  84. "href" => url_from_spec(upload, opts.base_url, url_spec)
  85. }
  86. |> Maps.put_if_present("width", upload.width)
  87. |> Maps.put_if_present("height", upload.height)
  88. ],
  89. "name" => description
  90. }
  91. |> Maps.put_if_present("blurhash", upload.blurhash)}
  92. else
  93. {:description_limit, _} ->
  94. {:error, :description_too_long}
  95. {:error, error} ->
  96. Logger.error(
  97. "#{__MODULE__} store (using #{inspect(opts.uploader)}) failed: #{inspect(error)}"
  98. )
  99. {:error, error}
  100. end
  101. end
  102. def char_unescaped?(char) do
  103. URI.char_unreserved?(char) or char == ?/
  104. end
  105. defp get_opts(opts) do
  106. {size_limit, activity_type} =
  107. case Keyword.get(opts, :type) do
  108. :banner ->
  109. {Pleroma.Config.get!([:instance, :banner_upload_limit]), "Image"}
  110. :avatar ->
  111. {Pleroma.Config.get!([:instance, :avatar_upload_limit]), "Image"}
  112. :background ->
  113. {Pleroma.Config.get!([:instance, :background_upload_limit]), "Image"}
  114. _ ->
  115. {Pleroma.Config.get!([:instance, :upload_limit]), "Document"}
  116. end
  117. %{
  118. activity_type: Keyword.get(opts, :activity_type, activity_type),
  119. size_limit: Keyword.get(opts, :size_limit, size_limit),
  120. uploader: Keyword.get(opts, :uploader, Pleroma.Config.get([__MODULE__, :uploader])),
  121. filters: Keyword.get(opts, :filters, Pleroma.Config.get([__MODULE__, :filters])),
  122. description: Keyword.get(opts, :description),
  123. base_url: base_url()
  124. }
  125. end
  126. defp prepare_upload(%Plug.Upload{} = file, opts) do
  127. with :ok <- check_file_size(file.path, opts.size_limit) do
  128. {:ok,
  129. %__MODULE__{
  130. id: UUID.generate(),
  131. name: file.filename,
  132. tempfile: file.path,
  133. content_type: file.content_type
  134. }}
  135. end
  136. end
  137. defp prepare_upload(%{img: "data:image/" <> image_data}, opts) do
  138. parsed = Regex.named_captures(~r/(?<filetype>jpeg|png|gif);base64,(?<data>.*)/, image_data)
  139. data = Base.decode64!(parsed["data"], ignore: :whitespace)
  140. hash = Base.encode16(:crypto.hash(:sha256, data), lower: true)
  141. with :ok <- check_binary_size(data, opts.size_limit),
  142. tmp_path <- tempfile_for_image(data),
  143. {:ok, %{mime_type: content_type}} <-
  144. Majic.perform({:bytes, data}, pool: Pleroma.MajicPool),
  145. [ext | _] <- MIME.extensions(content_type) do
  146. {:ok,
  147. %__MODULE__{
  148. id: UUID.generate(),
  149. name: hash <> "." <> ext,
  150. tempfile: tmp_path,
  151. content_type: content_type
  152. }}
  153. end
  154. end
  155. # For Mix.Tasks.MigrateLocalUploads
  156. defp prepare_upload(%__MODULE__{tempfile: path} = upload, _opts) do
  157. with {:ok, %{mime_type: content_type}} <- Majic.perform(path, pool: Pleroma.MajicPool) do
  158. {:ok, %__MODULE__{upload | content_type: content_type}}
  159. end
  160. end
  161. defp check_binary_size(binary, size_limit)
  162. when is_integer(size_limit) and size_limit > 0 and byte_size(binary) >= size_limit do
  163. {:error, :file_too_large}
  164. end
  165. defp check_binary_size(_, _), do: :ok
  166. defp check_file_size(path, size_limit) when is_integer(size_limit) and size_limit > 0 do
  167. with {:ok, %{size: size}} <- File.stat(path),
  168. true <- size <= size_limit do
  169. :ok
  170. else
  171. false -> {:error, :file_too_large}
  172. error -> error
  173. end
  174. end
  175. defp check_file_size(_, _), do: :ok
  176. # Creates a tempfile using the Plug.Upload Genserver which cleans them up
  177. # automatically.
  178. defp tempfile_for_image(data) do
  179. {:ok, tmp_path} = Plug.Upload.random_file("profile_pics")
  180. {:ok, tmp_file} = File.open(tmp_path, [:write, :raw, :binary])
  181. IO.binwrite(tmp_file, data)
  182. tmp_path
  183. end
  184. defp url_from_spec(%__MODULE__{name: name}, base_url, {:file, path}) do
  185. path =
  186. URI.encode(path, &char_unescaped?/1) <>
  187. if Pleroma.Config.get([__MODULE__, :link_name], false) do
  188. "?name=#{URI.encode(name, &char_unescaped?/1)}"
  189. else
  190. ""
  191. end
  192. [base_url, path]
  193. |> Path.join()
  194. end
  195. defp url_from_spec(_upload, _base_url, {:url, url}), do: url
  196. def base_url do
  197. uploader = Config.get([Pleroma.Upload, :uploader])
  198. upload_base_url = Config.get([Pleroma.Upload, :base_url])
  199. public_endpoint = Config.get([uploader, :public_endpoint])
  200. case uploader do
  201. Pleroma.Uploaders.Local ->
  202. upload_base_url || Pleroma.Web.Endpoint.url() <> "/media/"
  203. Pleroma.Uploaders.S3 ->
  204. bucket = Config.get([Pleroma.Uploaders.S3, :bucket])
  205. truncated_namespace = Config.get([Pleroma.Uploaders.S3, :truncated_namespace])
  206. namespace = Config.get([Pleroma.Uploaders.S3, :bucket_namespace])
  207. bucket_with_namespace =
  208. cond do
  209. !is_nil(truncated_namespace) ->
  210. truncated_namespace
  211. !is_nil(namespace) ->
  212. namespace <> ":" <> bucket
  213. true ->
  214. bucket
  215. end
  216. if public_endpoint do
  217. Path.join([public_endpoint, bucket_with_namespace])
  218. else
  219. Path.join([upload_base_url, bucket_with_namespace])
  220. end
  221. _ ->
  222. public_endpoint || upload_base_url || Pleroma.Web.Endpoint.url() <> "/media/"
  223. end
  224. end
  225. end