Update CHANGELOG
[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 # The file name is re-encoded with S3's constraints here to comply with previous
10 # links with less strict filenames
11 def get_file(file) do
12 config = Pleroma.Config.get([__MODULE__])
13 bucket = Keyword.fetch!(config, :bucket)
14
15 bucket_with_namespace =
16 cond do
17 truncated_namespace = Keyword.get(config, :truncated_namespace) ->
18 truncated_namespace
19
20 namespace = Keyword.get(config, :bucket_namespace) ->
21 namespace <> ":" <> bucket
22
23 true ->
24 bucket
25 end
26
27 {:ok,
28 {:url,
29 Path.join([
30 Keyword.fetch!(config, :public_endpoint),
31 bucket_with_namespace,
32 strict_encode(URI.decode(file))
33 ])}}
34 end
35
36 def put_file(%Pleroma.Upload{} = upload) do
37 config = Pleroma.Config.get([__MODULE__])
38 bucket = Keyword.get(config, :bucket)
39
40 {:ok, file_data} = File.read(upload.tempfile)
41
42 s3_name = strict_encode(upload.path)
43
44 op =
45 ExAws.S3.put_object(bucket, s3_name, file_data, [
46 {:acl, :public_read},
47 {:content_type, upload.content_type}
48 ])
49
50 case ExAws.request(op) do
51 {:ok, _} ->
52 {:ok, {:file, s3_name}}
53
54 error ->
55 Logger.error("#{__MODULE__}: #{inspect(error)}")
56 {:error, "S3 Upload failed"}
57 end
58 end
59
60 @regex Regex.compile!("[^0-9a-zA-Z!.*/'()_-]")
61 def strict_encode(name) do
62 String.replace(name, @regex, "-")
63 end
64 end