Normalize file extension for uploaded files
authorFrancis Dinh <normandy@firemail.cc>
Thu, 21 Jun 2018 18:04:12 +0000 (14:04 -0400)
committerFrancis Dinh <normandy@firemail.cc>
Thu, 21 Jun 2018 18:04:12 +0000 (14:04 -0400)
lib/pleroma/upload.ex
test/fixtures/test.txt [new file with mode: 0644]
test/upload_test.exs

index 43df0d418f193ff8e1dcb9a1856915dc8879ea20..6793c46719b6a87e689c65a69f93e5ab14a6eb3b 100644 (file)
@@ -110,20 +110,20 @@ defmodule Pleroma.Upload do
     if should_dedupe do
       create_name(uuid, List.last(String.split(file.filename, ".")), type)
     else
-      unless String.contains?(file.filename, ".") do
-        case type do
-          "image/png" -> file.filename <> ".png"
-          "image/jpeg" -> file.filename <> ".jpg"
-          "image/gif" -> file.filename <> ".gif"
-          "video/webm" -> file.filename <> ".webm"
-          "video/mp4" -> file.filename <> ".mp4"
-          "audio/mpeg" -> file.filename <> ".mp3"
-          "audio/ogg" -> file.filename <> ".ogg"
-          "audio/wav" -> file.filename <> ".wav"
-          _ -> file.filename
+      parts = String.split(file.filename, ".")
+
+      new_filename =
+        if length(parts) > 1 do
+          Enum.drop(parts, -1) |> Enum.join(".")
+        else
+          Enum.join(parts)
         end
-      else
-        file.filename
+
+      case type do
+        "application/octet-stream" -> file.filename
+        "audio/mpeg" -> new_filename <> ".mp3"
+        "image/jpeg" -> new_filename <> ".jpg"
+        _ -> Enum.join([new_filename, String.split(type, "/") |> List.last()], ".")
       end
     end
   end
diff --git a/test/fixtures/test.txt b/test/fixtures/test.txt
new file mode 100644 (file)
index 0000000..e9ea42a
--- /dev/null
@@ -0,0 +1 @@
+this is a text file
index 09aa5e068b53c0c68f9326dfbada292a58dfbe22..d273ea5f60f271273fdf24a6abe0e46c35d4995c 100644 (file)
@@ -56,5 +56,31 @@ defmodule Pleroma.UploadTest do
       data = Upload.store(file, false)
       assert data["name"] == "an [image.jpg"
     end
+
+    test "fixes incorrect file extension" do
+      File.cp!("test/fixtures/image.jpg", "test/fixtures/image_tmp.jpg")
+
+      file = %Plug.Upload{
+        content_type: "image/jpg",
+        path: Path.absname("test/fixtures/image_tmp.jpg"),
+        filename: "an [image.blah"
+      }
+
+      data = Upload.store(file, false)
+      assert data["name"] == "an [image.jpg"
+    end
+
+    test "don't modify filename of an unknown type" do
+      File.cp("test/fixtures/test.txt", "test/fixtures/test_tmp.txt")
+
+      file = %Plug.Upload{
+        content_type: "text/plain",
+        path: Path.absname("test/fixtures/test_tmp.txt"),
+        filename: "test.txt"
+      }
+
+      data = Upload.store(file, false)
+      assert data["name"] == "test.txt"
+    end
   end
 end