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