Removed file as requested
[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 links with less strict filenames
10 def get_file(file) do
11 config = Pleroma.Config.get([__MODULE__])
12
13 {:ok,
14 {:url,
15 Path.join([
16 Keyword.fetch!(config, :public_endpoint),
17 Keyword.fetch!(config, :bucket),
18 strict_encode(URI.decode(file))
19 ])}}
20 end
21
22 def put_file(upload = %Pleroma.Upload{}) do
23 config = Pleroma.Config.get([__MODULE__])
24 bucket = Keyword.get(config, :bucket)
25
26 {:ok, file_data} = File.read(upload.tempfile)
27
28 s3_name = strict_encode(upload.path)
29
30 op =
31 ExAws.S3.put_object(bucket, s3_name, file_data, [
32 {:acl, :public_read},
33 {:content_type, upload.content_type}
34 ])
35
36 case ExAws.request(op) do
37 {:ok, _} ->
38 {:ok, {:file, s3_name}}
39
40 error ->
41 Logger.error("#{__MODULE__}: #{inspect(error)}")
42 {:error, "S3 Upload failed"}
43 end
44 end
45
46 @regex Regex.compile!("[^0-9a-zA-Z!.*/'()_-]")
47 def strict_encode(name) do
48 String.replace(name, @regex, "-")
49 end
50 end