Merge branch 'hotfix/delete-activities' into 'develop'
[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 if namespace = Keyword.get(config, :bucket_namespace) do
17 namespace <> ":" <> bucket
18 else
19 bucket
20 end
21
22 {:ok,
23 {:url,
24 Path.join([
25 Keyword.fetch!(config, :public_endpoint),
26 bucket_with_namespace,
27 strict_encode(URI.decode(file))
28 ])}}
29 end
30
31 def put_file(%Pleroma.Upload{} = upload) do
32 config = Pleroma.Config.get([__MODULE__])
33 bucket = Keyword.get(config, :bucket)
34
35 {:ok, file_data} = File.read(upload.tempfile)
36
37 s3_name = strict_encode(upload.path)
38
39 op =
40 ExAws.S3.put_object(bucket, s3_name, file_data, [
41 {:acl, :public_read},
42 {:content_type, upload.content_type}
43 ])
44
45 case ExAws.request(op) do
46 {:ok, _} ->
47 {:ok, {:file, s3_name}}
48
49 error ->
50 Logger.error("#{__MODULE__}: #{inspect(error)}")
51 {:error, "S3 Upload failed"}
52 end
53 end
54
55 @regex Regex.compile!("[^0-9a-zA-Z!.*/'()_-]")
56 def strict_encode(name) do
57 String.replace(name, @regex, "-")
58 end
59 end