branch
[akkoma] / lib / pleroma / uploaders / s3.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 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 def get_file(file) do
14 config = Config.get([__MODULE__])
15 bucket = Keyword.fetch!(config, :bucket)
16
17 bucket_with_namespace =
18 cond do
19 truncated_namespace = Keyword.get(config, :truncated_namespace) ->
20 truncated_namespace
21
22 namespace = Keyword.get(config, :bucket_namespace) ->
23 namespace <> ":" <> bucket
24
25 true ->
26 bucket
27 end
28
29 {:ok,
30 {:url,
31 Path.join([
32 Keyword.fetch!(config, :public_endpoint),
33 bucket_with_namespace,
34 strict_encode(URI.decode(file))
35 ])}}
36 end
37
38 def put_file(%Pleroma.Upload{} = upload) do
39 config = Config.get([__MODULE__])
40 bucket = Keyword.get(config, :bucket)
41 streaming = Keyword.get(config, :streaming_enabled)
42
43 s3_name = strict_encode(upload.path)
44
45 op =
46 if streaming do
47 upload.tempfile
48 |> ExAws.S3.Upload.stream_file()
49 |> ExAws.S3.upload(bucket, s3_name, [
50 {:acl, :public_read},
51 {:content_type, upload.content_type}
52 ])
53 else
54 {:ok, file_data} = File.read(upload.tempfile)
55
56 ExAws.S3.put_object(bucket, s3_name, file_data, [
57 {:acl, :public_read},
58 {:content_type, upload.content_type}
59 ])
60 end
61
62 case ExAws.request(op) do
63 {:ok, _} ->
64 {:ok, {:file, s3_name}}
65
66 error ->
67 Logger.error("#{__MODULE__}: #{inspect(error)}")
68 {:error, "S3 Upload failed"}
69 end
70 end
71
72 @regex Regex.compile!("[^0-9a-zA-Z!.*/'()_-]")
73 def strict_encode(name) do
74 String.replace(name, @regex, "-")
75 end
76 end