1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Uploaders.S3 do
6 @behaviour Pleroma.Uploaders.Uploader
9 @ex_aws_impl Application.compile_env(:pleroma, [__MODULE__, :ex_aws_impl], ExAws)
10 @config_impl Application.compile_env(:pleroma, [__MODULE__, :config_impl], Pleroma.Config)
12 # The file name is re-encoded with S3's constraints here to comply with previous
13 # links with less strict filenames
19 Pleroma.Upload.base_url(),
20 strict_encode(URI.decode(file))
25 def put_file(%Pleroma.Upload{} = upload) do
26 config = @config_impl.get([__MODULE__])
27 bucket = Keyword.get(config, :bucket)
28 streaming = Keyword.get(config, :streaming_enabled)
30 s3_name = strict_encode(upload.path)
36 |> ExAws.S3.Upload.stream_file()
37 |> ExAws.S3.upload(bucket, s3_name, [
39 {:content_type, upload.content_type}
42 if Application.get_env(:tesla, :adapter) == Tesla.Adapter.Gun do
43 # set s3 upload timeout to respect :upload pool timeout
44 # timeout should be slightly larger, so s3 can retry upload on fail
45 timeout = Pleroma.HTTP.AdapterHelper.Gun.pool_timeout(:upload) + 1_000
46 opts = Keyword.put(op.opts, :timeout, timeout)
47 Map.put(op, :opts, opts)
52 {:ok, file_data} = File.read(upload.tempfile)
54 ExAws.S3.put_object(bucket, s3_name, file_data, [
56 {:content_type, upload.content_type}
60 case @ex_aws_impl.request(op) do
62 {:ok, {:file, s3_name}}
65 Logger.error("#{__MODULE__}: #{inspect(error)}")
66 {:error, "S3 Upload failed"}
71 def delete_file(file) do
74 |> ExAws.S3.delete_object(file)
75 |> @ex_aws_impl.request()
77 {:ok, %{status_code: 204}} -> :ok
78 error -> {:error, inspect(error)}
82 @regex Regex.compile!("[^0-9a-zA-Z!.*/'()_-]")
83 def strict_encode(name) do
84 String.replace(name, @regex, "-")
88 defmodule Pleroma.Uploaders.S3.ExAwsAPI do
89 @callback request(op :: ExAws.Operation.t()) :: {:ok, ExAws.Operation.t()} | {:error, term()}