total rebase
[anni] / lib / pleroma / uploaders / s3.ex
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
5 defmodule Pleroma.Uploaders.S3 do
6   @behaviour Pleroma.Uploaders.Uploader
7   require Logger
8
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)
11
12   # The file name is re-encoded with S3's constraints here to comply with previous
13   # links with less strict filenames
14   @impl true
15   def get_file(file) do
16     {:ok,
17      {:url,
18       Path.join([
19         Pleroma.Upload.base_url(),
20         strict_encode(URI.decode(file))
21       ])}}
22   end
23
24   @impl true
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)
29
30     s3_name = strict_encode(upload.path)
31
32     op =
33       if streaming do
34         op =
35           upload.tempfile
36           |> ExAws.S3.Upload.stream_file()
37           |> ExAws.S3.upload(bucket, s3_name, [
38             {:acl, :public_read},
39             {:content_type, upload.content_type}
40           ])
41
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)
48         else
49           op
50         end
51       else
52         {:ok, file_data} = File.read(upload.tempfile)
53
54         ExAws.S3.put_object(bucket, s3_name, file_data, [
55           {:acl, :public_read},
56           {:content_type, upload.content_type}
57         ])
58       end
59
60     case @ex_aws_impl.request(op) do
61       {:ok, _} ->
62         {:ok, {:file, s3_name}}
63
64       error ->
65         Logger.error("#{__MODULE__}: #{inspect(error)}")
66         {:error, "S3 Upload failed"}
67     end
68   end
69
70   @impl true
71   def delete_file(file) do
72     [__MODULE__, :bucket]
73     |> @config_impl.get()
74     |> ExAws.S3.delete_object(file)
75     |> @ex_aws_impl.request()
76     |> case do
77       {:ok, %{status_code: 204}} -> :ok
78       error -> {:error, inspect(error)}
79     end
80   end
81
82   @regex Regex.compile!("[^0-9a-zA-Z!.*/'()_-]")
83   def strict_encode(name) do
84     String.replace(name, @regex, "-")
85   end
86 end
87
88 defmodule Pleroma.Uploaders.S3.ExAwsAPI do
89   @callback request(op :: ExAws.Operation.t()) :: {:ok, ExAws.Operation.t()} | {:error, term()}
90 end