19832a7ecc456e38390d1d931370bb1402d3a2dd
[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(upload = %Pleroma.Upload{}) do
19 config = Pleroma.Config.get([__MODULE__])
20 bucket = Keyword.get(config, :bucket)
21
22 {:ok, file_data} = File.read(upload.tempfile)
23
24 s3_name = strict_encode(upload.path)
25
26 op =
27 ExAws.S3.put_object(bucket, s3_name, file_data, [
28 {:acl, :public_read},
29 {:content_type, upload.content_type}
30 ])
31
32 case ExAws.request(op) do
33 {:ok, _} ->
34 {:ok, {:file, s3_name}}
35
36 error ->
37 Logger.error("#{__MODULE__}: #{inspect(error)}")
38 {:error, "S3 Upload failed"}
39 end
40 end
41
42 @regex Regex.compile!("[^0-9a-zA-Z!.*/'()_-]")
43 def strict_encode(name) do
44 String.replace(name, @regex, "-")
45 end
46 end