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.

258 lines
8.3KB

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