2d1ddef757fe741b9d0d48ba1b28e22fb8da6b5a
[akkoma] / lib / pleroma / uploaders / s3.ex
1 defmodule Pleroma.Uploaders.S3 do
2 @behaviour Pleroma.Uploaders.Uploader
3 require Logger
4
5 # The file name is re-encoded with S3's constraints here to comply with previous links with less strict filenames
6 def get_file(file) do
7 config = Pleroma.Config.get([__MODULE__])
8
9 {:ok,
10 {:url,
11 Path.join([
12 Keyword.fetch!(config, :public_endpoint),
13 Keyword.fetch!(config, :bucket),
14 strict_encode(URI.decode(file))
15 ])}}
16 end
17
18 def put_file(name, uuid, path, content_type, _opts) do
19 config = Pleroma.Config.get([__MODULE__])
20 bucket = Keyword.get(config, :bucket)
21
22 {:ok, file_data} = File.read(path)
23
24 File.rm!(path)
25
26 s3_name = "#{uuid}/#{strict_encode(name)}"
27
28 op =
29 ExAws.S3.put_object(bucket, s3_name, file_data, [
30 {:acl, :public_read},
31 {:content_type, content_type}
32 ])
33
34 case ExAws.request(op) do
35 {:ok, _} ->
36 {:ok, {:file, s3_name}}
37
38 error ->
39 Logger.error("#{__MODULE__}: #{inspect(error)}")
40 {:error, "S3 Upload failed"}
41 end
42 end
43
44 @regex Regex.compile!("[^0-9a-zA-Z!.*/'()_-]")
45 def strict_encode(name) do
46 String.replace(name, @regex, "-")
47 end
48 end