1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Uploaders.S3 do
6 @behaviour Pleroma.Uploaders.Uploader
11 # The file name is re-encoded with S3's constraints here to comply with previous
12 # links with less strict filenames
18 Pleroma.Upload.base_url(),
19 strict_encode(URI.decode(file))
24 def put_file(%Pleroma.Upload{} = upload) do
25 config = Config.get([__MODULE__])
26 bucket = Keyword.get(config, :bucket)
27 streaming = Keyword.get(config, :streaming_enabled)
29 s3_name = strict_encode(upload.path)
35 |> ExAws.S3.Upload.stream_file()
36 |> ExAws.S3.upload(bucket, s3_name, [
38 {:content_type, upload.content_type}
41 if Application.get_env(:tesla, :adapter) == Tesla.Adapter.Gun do
42 # set s3 upload timeout to respect :upload pool timeout
43 # timeout should be slightly larger, so s3 can retry upload on fail
44 timeout = Pleroma.HTTP.AdapterHelper.Gun.pool_timeout(:upload) + 1_000
45 opts = Keyword.put(op.opts, :timeout, timeout)
46 Map.put(op, :opts, opts)
51 {:ok, file_data} = File.read(upload.tempfile)
53 ExAws.S3.put_object(bucket, s3_name, file_data, [
55 {:content_type, upload.content_type}
59 case ExAws.request(op) do
61 {:ok, {:file, s3_name}}
64 Logger.error("#{__MODULE__}: #{inspect(error)}")
65 {:error, "S3 Upload failed"}
70 def delete_file(file) do
73 |> ExAws.S3.delete_object(file)
76 {:ok, %{status_code: 204}} -> :ok
77 error -> {:error, inspect(error)}
81 @regex Regex.compile!("[^0-9a-zA-Z!.*/'()_-]")
82 def strict_encode(name) do
83 String.replace(name, @regex, "-")