Add Uploads.
authorRoger Braun <roger@rogerbraun.net>
Tue, 28 Mar 2017 23:39:01 +0000 (01:39 +0200)
committerRoger Braun <roger@rogerbraun.net>
Tue, 28 Mar 2017 23:39:01 +0000 (01:39 +0200)
config/config.exs
config/test.exs
lib/pleroma/upload.ex [new file with mode: 0644]
test/fixtures/image.jpg [new file with mode: 0644]
test/upload_test.exs [new file with mode: 0644]

index 8eea4dd0a1d605aedba6a1dfc68dacd9172d5e07..bf050197fed293e627922ae4c2497b356ed54d14 100644 (file)
@@ -9,6 +9,9 @@ use Mix.Config
 config :pleroma,
   ecto_repos: [Pleroma.Repo]
 
+config :pleroma, Pleroma.Upload,
+  uploads: "uploads"
+
 # Configures the endpoint
 config :pleroma, Pleroma.Web.Endpoint,
   url: [host: "localhost"],
index 07f49d3e9eb85c0a081fbcf86029fd19ee5408b9..f5d6f240d4fd20ff2597923d2b0ce5e79fc3518a 100644 (file)
@@ -9,6 +9,9 @@ config :pleroma, Pleroma.Web.Endpoint,
 # Print only warnings and errors during test
 config :logger, level: :warn
 
+config :pleroma, Pleroma.Upload,
+  uploads: "test/uploads"
+
 # Configure your database
 config :pleroma, Pleroma.Repo,
   adapter: Ecto.Adapters.Postgres,
diff --git a/lib/pleroma/upload.ex b/lib/pleroma/upload.ex
new file mode 100644 (file)
index 0000000..43ebe98
--- /dev/null
@@ -0,0 +1,30 @@
+defmodule Pleroma.Upload do
+  def store(%Plug.Upload{} = file) do
+    uuid = Ecto.UUID.generate
+    upload_folder = Path.join(upload_path(), uuid)
+    File.mkdir_p!(upload_folder)
+    result_file = Path.join(upload_folder, file.filename)
+    File.cp!(file.path, result_file)
+
+    %{
+      "type" => "Image",
+      "href" => url_for(Path.join(uuid, file.filename)),
+      "name" => file.filename,
+      "uuid" => uuid
+    }
+  end
+
+  defp upload_path do
+    Application.get_env(:pleroma, Pleroma.Upload)
+    |> Keyword.fetch!(:uploads)
+  end
+
+  defp url_for(file) do
+    host =
+      Application.get_env(:pleroma, Pleroma.Web.Endpoint)
+      |> Keyword.fetch!(:url)
+      |> Keyword.fetch!(:host)
+
+    "https://#{host}/media/#{file}"
+  end
+end
diff --git a/test/fixtures/image.jpg b/test/fixtures/image.jpg
new file mode 100644 (file)
index 0000000..09834bb
Binary files /dev/null and b/test/fixtures/image.jpg differ
diff --git a/test/upload_test.exs b/test/upload_test.exs
new file mode 100644 (file)
index 0000000..e8c9543
--- /dev/null
@@ -0,0 +1,12 @@
+defmodule Pleroma.UploadTest do
+  alias Pleroma.Upload
+  use Pleroma.DataCase
+
+  describe "Storing a file" do
+    test "copies the file to the configured folder" do
+      file = %Plug.Upload{content_type: "image/jpg", path: Path.absname("test/fixtures/image.jpg"), filename: "an_image.jpg"}
+      data = Upload.store(file)
+      assert data["name"] == "an_image.jpg"
+    end
+  end
+end