Merge branch 'develop' into 'fix/mix-task-uploads-moduledoc'
[akkoma] / lib / pleroma / uploaders / s3.ex
index 87322753dd97b29e0ad23226a1d2819b7e53c604..19832a7ecc456e38390d1d931370bb1402d3a2dd 100644 (file)
@@ -1,28 +1,46 @@
 defmodule Pleroma.Uploaders.S3 do
   @behaviour Pleroma.Uploaders.Uploader
+  require Logger
 
-  def put_file(name, uuid, path, content_type, _should_dedupe) do
-    settings = Application.get_env(:pleroma, Pleroma.Uploaders.S3)
-    bucket = Keyword.fetch!(settings, :bucket)
-    public_endpoint = Keyword.fetch!(settings, :public_endpoint)
+  # The file name is re-encoded with S3's constraints here to comply with previous links with less strict filenames
+  def get_file(file) do
+    config = Pleroma.Config.get([__MODULE__])
 
-    {:ok, file_data} = File.read(path)
+    {:ok,
+     {:url,
+      Path.join([
+        Keyword.fetch!(config, :public_endpoint),
+        Keyword.fetch!(config, :bucket),
+        strict_encode(URI.decode(file))
+      ])}}
+  end
+
+  def put_file(upload = %Pleroma.Upload{}) do
+    config = Pleroma.Config.get([__MODULE__])
+    bucket = Keyword.get(config, :bucket)
 
-    File.rm!(path)
+    {:ok, file_data} = File.read(upload.tempfile)
 
-    s3_name = "#{uuid}/#{encode(name)}"
+    s3_name = strict_encode(upload.path)
 
-    {:ok, _} =
+    op =
       ExAws.S3.put_object(bucket, s3_name, file_data, [
         {:acl, :public_read},
-        {:content_type, content_type}
+        {:content_type, upload.content_type}
       ])
-      |> ExAws.request()
 
-    {:ok, "#{public_endpoint}/#{bucket}/#{s3_name}"}
+    case ExAws.request(op) do
+      {:ok, _} ->
+        {:ok, {:file, s3_name}}
+
+      error ->
+        Logger.error("#{__MODULE__}: #{inspect(error)}")
+        {:error, "S3 Upload failed"}
+    end
   end
 
-  defp encode(name) do
-    String.replace(name, ~r/[^0-9a-zA-Z!.*'()_-]/, "-")
+  @regex Regex.compile!("[^0-9a-zA-Z!.*/'()_-]")
+  def strict_encode(name) do
+    String.replace(name, @regex, "-")
   end
 end